Skip to content

Execution

execution

Agent execution infrastructure for GEPA evolution.

Contains the agent executor for unified ADK agent execution and the trial builder for constructing reflection dataset records.

Anticipated growth: execution middleware, custom session service adapters, batch execution strategies.

ATTRIBUTE DESCRIPTION
AgentExecutor

Unified executor for all ADK agent types.

SessionNotFoundError

Raised when session lookup fails.

TrialBuilder

Builder for trial records from evaluation results.

Examples:

Execute an agent and build a trial record:

from gepa_adk.adapters.execution import AgentExecutor, TrialBuilder

executor = AgentExecutor(session_service=session_service)
result = await executor.execute(agent, user_content)
See Also
Notes

This package encapsulates agent execution and trial-building infrastructure.

AgentExecutor

Unified agent execution adapter.

Provides a single execution path for all ADK agent types (generator, critic, reflection) with consistent session management, event capture, and result handling.

ATTRIBUTE DESCRIPTION
retry_policy

Policy for retrying a transient session-service error such as database is locked.

TYPE: RetryPolicy

_session_service

ADK session service for state management.

TYPE: BaseSessionService

_app_name

Application name for ADK runner.

TYPE: str

Examples:

Basic usage:

executor = AgentExecutor()
result = await executor.execute_agent(
    agent=my_agent,
    input_text="Hello, world!",
)
if result.status == ExecutionStatus.SUCCESS:
    print(f"Output: {result.extracted_value}")

With custom session service:

from google.adk.sessions import InMemorySessionService

session_service = InMemorySessionService()
executor = AgentExecutor(session_service=session_service)
Notes

Adapter implements AgentExecutorProtocol for dependency injection and testing. All ADK-specific logic is encapsulated here.

Source code in src/gepa_adk/adapters/execution/agent_executor.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
class AgentExecutor:
    """Unified agent execution adapter.

    Provides a single execution path for all ADK agent types (generator, critic,
    reflection) with consistent session management, event capture, and result
    handling.

    Attributes:
        retry_policy (RetryPolicy): Policy for retrying a transient
            session-service error such as ``database is locked``.
        _session_service (BaseSessionService): ADK session service for state management.
        _app_name (str): Application name for ADK runner.

    Examples:
        Basic usage:

        ```python
        executor = AgentExecutor()
        result = await executor.execute_agent(
            agent=my_agent,
            input_text="Hello, world!",
        )
        if result.status == ExecutionStatus.SUCCESS:
            print(f"Output: {result.extracted_value}")
        ```

        With custom session service:

        ```python
        from google.adk.sessions import InMemorySessionService

        session_service = InMemorySessionService()
        executor = AgentExecutor(session_service=session_service)
        ```

    Notes:
        Adapter implements AgentExecutorProtocol for dependency injection
        and testing. All ADK-specific logic is encapsulated here.
    """

    def __init__(
        self,
        session_service: BaseSessionService | None = None,
        app_name: str = "gepa_executor",
        retry_policy: RetryPolicy | None = None,
    ) -> None:
        """Initialize AgentExecutor.

        Args:
            session_service: ADK session service for state management.
                If None, creates an InMemorySessionService.
            app_name: Application name for ADK runner. Defaults to "gepa_executor".
            retry_policy: Policy for retrying a transient session-service
                error. If None, uses ``RetryPolicy()`` (three attempts,
                0.5 s backoff, doubling).

        Examples:
            Default initialization:

            ```python
            executor = AgentExecutor()
            ```

            With custom app name:

            ```python
            executor = AgentExecutor(app_name="my_app")
            ```

            With a custom retry policy:

            ```python
            executor = AgentExecutor(
                session_service=sqlite_service,
                retry_policy=RetryPolicy(max_attempts=5),
            )
            ```

        Notes:
            Creates a shared executor that uses the session service for all
            agent executions, allowing session state to be shared between
            executions when desired.
        """
        self._session_service = session_service or InMemorySessionService()
        self._app_name = app_name
        self.retry_policy = retry_policy or RetryPolicy()
        self._logger = logger.bind(component="AgentExecutor", app_name=app_name)

    async def _create_session(
        self,
        user_id: str,
        session_state: dict[str, Any] | None = None,
    ) -> Session:
        """Create a new session with optional initial state.

        Args:
            user_id: User identifier for the session.
            session_state: Initial state to inject into the session.

        Returns:
            Created ADK Session object.

        Notes:
            Optional session state enables template variable substitution in
            agent instructions (e.g., {component_text} and {trials}).
        """
        session_id = f"exec_{uuid4()}"

        self._logger.debug(
            "session.creating",
            session_id=session_id,
            user_id=user_id,
            has_initial_state=session_state is not None,
        )

        session = await self._session_service.create_session(
            app_name=self._app_name,
            user_id=user_id,
            session_id=session_id,
            state=session_state,
        )

        self._logger.debug(
            "session.created",
            session_id=session.id,
        )

        return session

    async def _get_session(self, session_id: str, user_id: str) -> Session:
        """Retrieve an existing session by ID.

        Args:
            session_id: The session ID to retrieve.
            user_id: User identifier for the session.

        Returns:
            Existing ADK Session object.

        Raises:
            SessionNotFoundError: If the session does not exist.

        Notes:
            Only performs strict existence checks for sessions that must
            already exist. Callers use this to fail fast instead of creating
            a new session. For get-or-create semantics, use _get_or_create_session.
        """
        session = await self._session_service.get_session(
            app_name=self._app_name,
            user_id=user_id,
            session_id=session_id,
        )

        if session is None:
            raise SessionNotFoundError(session_id)

        self._logger.debug(
            "session.retrieved",
            session_id=session_id,
        )

        return session

    async def _get_or_create_session(
        self,
        session_id: str,
        user_id: str,
        session_state: dict[str, Any] | None = None,
    ) -> Session:
        """Get an existing session or create a new one with the specified ID.

        Implements "get or create" semantics for session management. If the
        session exists, returns it. If not, creates a new session with the
        specified ID and optional initial state.

        Args:
            session_id: The session ID to retrieve or create.
            user_id: User identifier for the session.
            session_state: Initial state to inject if creating a new session.
                Ignored if session already exists.

        Returns:
            ADK Session object (existing or newly created).

        Notes:
            Only applies initial state when creating new sessions. Existing
            sessions retain their current state regardless of session_state
            parameter.
        """
        # Try to get existing session first
        session = await self._session_service.get_session(
            app_name=self._app_name,
            user_id=user_id,
            session_id=session_id,
        )

        if session is not None:
            self._logger.debug(
                "session.retrieved",
                session_id=session_id,
            )
            return session

        # Session doesn't exist, create it with the specified ID
        self._logger.debug(
            "session.creating_with_id",
            session_id=session_id,
            user_id=user_id,
            has_initial_state=session_state is not None,
        )

        session = await self._session_service.create_session(
            app_name=self._app_name,
            user_id=user_id,
            session_id=session_id,
            state=session_state,
        )

        self._logger.debug(
            "session.created",
            session_id=session.id,
        )

        return session

    def _apply_overrides(
        self,
        agent: Any,
        instruction_override: str | None,
        output_schema_override: Any | None,
    ) -> Any:
        """Apply instruction and schema overrides to create modified agent copy.

        Args:
            agent (Any): Original ADK LlmAgent.
            instruction_override (str | None): If provided, replaces agent instruction.
            output_schema_override (Any | None): If provided, replaces output schema.

        Returns:
            Modified agent copy (or original if no overrides).

        Notes:
            Copies the agent with ``model_copy(update=...)``, so every
            user-set field (description, callbacks, generate config,
            planner, sub-agents and so on) carries over. Only the
            overridden ``instruction`` and ``output_schema`` keys change.
            The original agent is never modified.
        """
        if instruction_override is None and output_schema_override is None:
            return agent

        updates: dict[str, Any] = {}
        if instruction_override is not None:
            updates["instruction"] = instruction_override
        if output_schema_override is not None:
            updates["output_schema"] = output_schema_override

        modified_agent = agent.model_copy(update=updates)

        self._logger.debug(
            "agent.overrides_applied",
            instruction_override=instruction_override is not None,
            schema_override=output_schema_override is not None,
        )

        return modified_agent

    def _build_content(
        self,
        input_text: str,
        input_content: types.Content | None = None,
    ) -> types.Content:
        """Build Content for agent execution.

        Assembles the Content object to send to the agent. If input_content
        is provided, uses it directly. Otherwise, wraps input_text in a
        Content with a single text Part.

        Args:
            input_text: Text input for the agent.
            input_content: Pre-assembled multimodal Content. Takes precedence
                over input_text when provided.

        Returns:
            Content object for agent execution.

        Notes:
            Serves as the central point for Content assembly, supporting
            both text-only (backward compatible) and multimodal inputs.
        """
        if input_content is not None:
            return input_content

        return types.Content(
            role="user",
            parts=[types.Part(text=input_text)],
        )

    async def _execute_runner(
        self,
        runner: Runner,
        session: Session,
        user_id: str,
        input_text: str,
        input_content: types.Content | None = None,
    ) -> list[Any]:
        """Execute the ADK Runner and capture events.

        Args:
            runner (Runner): ADK Runner instance.
            session (Session): ADK Session for execution.
            user_id (str): User identifier.
            input_text (str): User message to send (used if input_content is None).
            input_content (types.Content | None): Pre-assembled multimodal Content. Takes precedence
                over input_text when provided.

        Returns:
            List of captured ADK events.

        Notes:
            Orchestrates the core Runner.run_async() loop, capturing all
            events for later output extraction.
        """
        content = self._build_content(input_text, input_content)

        events: list[Any] = [
            event
            async for event in runner.run_async(
                user_id=user_id,
                session_id=session.id,
                new_message=content,
            )
        ]

        return events

    async def _execute_with_timeout(
        self,
        runner: Runner,
        session: Session,
        user_id: str,
        input_text: str,
        timeout_seconds: int,
        input_content: types.Content | None = None,
    ) -> tuple[list[Any], bool]:
        """Execute runner with timeout handling.

        Args:
            runner: ADK Runner instance.
            session: ADK Session for execution.
            user_id: User identifier.
            input_text: User message to send (used if input_content is None).
            timeout_seconds: Maximum execution time.
            input_content: Pre-assembled multimodal Content. Takes precedence
                over input_text when provided.

        Returns:
            Tuple of (captured_events, timed_out).

        Notes:
            On timeout, returns partial events captured before timeout.
            Uses asyncio.timeout for cancellation.
        """
        events: list[Any] = []
        timed_out = False

        try:
            async with asyncio.timeout(timeout_seconds):
                events = await self._execute_runner(
                    runner, session, user_id, input_text, input_content
                )
        except TimeoutError:
            timed_out = True
            self._logger.warning(
                "execution.timeout",
                session_id=session.id,
                timeout_seconds=timeout_seconds,
                events_captured=len(events),
            )

        return events, timed_out

    async def _extract_output(
        self,
        session: Session,
        events: list[Any],
        agent: Any,
    ) -> str | None:
        """Extract output from session state with event fallback.

        Args:
            session: ADK Session after execution.
            events: Captured events from execution.
            agent: Agent that was executed (for output_key).

        Returns:
            Extracted output string, or None if no output found.

        Notes:
            Output extraction prioritizes state-based approach (using
            output_key), then falls back to event-based extraction.
        """
        # Try state-based extraction first (if agent has output_key)
        output_key = getattr(agent, "output_key", None)
        if output_key:
            # Refresh session state
            refreshed_session = await self._session_service.get_session(
                app_name=self._app_name,
                user_id=session.user_id,
                session_id=session.id,
            )
            if refreshed_session and refreshed_session.state:
                state_output = extract_output_from_state(
                    refreshed_session.state, output_key
                )
                if state_output:
                    self._logger.debug(
                        "output.extracted_from_state",
                        output_key=output_key,
                    )
                    return state_output

        # Fallback to event-based extraction
        event_output = extract_final_output(events)
        if event_output:
            self._logger.debug("output.extracted_from_events")
            return event_output

        return None

    async def _open_session(
        self,
        user_id: str,
        session_state: dict[str, Any] | None,
        existing_session_id: str | None,
    ) -> Session:
        """Open the session for one execution attempt.

        Args:
            user_id: User identifier for the session.
            session_state: Initial state to inject into the session.
            existing_session_id: Session ID for get-or-create semantics, or
                None to create a fresh session.

        Returns:
            The ADK Session to run the attempt in.

        Notes:
            Called once per attempt, so a retried attempt without an
            ``existing_session_id`` runs in a fresh session.
        """
        if existing_session_id:
            return await self._get_or_create_session(
                existing_session_id, user_id, session_state
            )
        return await self._create_session(user_id, session_state)

    async def _retry_after(
        self,
        error: Exception,
        attempt: int,
        backoff: float,
        session: Session | None,
    ) -> bool:
        """Log and sleep before a retry when the error warrants one.

        Args:
            error: The exception the attempt raised.
            attempt: The 1-based number of the attempt that failed.
            backoff: Seconds to sleep before the next attempt.
            session: The attempt's session, or None if creation failed.

        Returns:
            True when the error is transient and attempts remain, after
            logging ``execution.retry`` and sleeping; False otherwise.

        Notes:
            Sleeps through ``asyncio.sleep`` so tests can patch it.
        """
        max_attempts = self.retry_policy.max_attempts
        if attempt >= max_attempts or not is_transient_session_error(error):
            return False
        self._logger.warning(
            "execution.retry",
            attempt=attempt,
            max_attempts=max_attempts,
            backoff_seconds=backoff,
            error=str(error),
            session_id=session.id if session else None,
        )
        await asyncio.sleep(backoff)
        return True

    async def _run_with_retry(
        self,
        runner: Runner,
        user_id: str,
        input_text: str,
        input_content: types.Content | None,
        session_state: dict[str, Any] | None,
        existing_session_id: str | None,
        timeout_seconds: int,
    ) -> tuple[Session | None, list[Any], bool, str | None, int]:
        """Open a session and run the agent, retrying transient errors.

        Args:
            runner (Runner): ADK Runner for the (possibly overridden) agent.
            user_id (str): User identifier.
            input_text (str): User message to send.
            input_content (types.Content | None): Pre-assembled multimodal Content, if any.
            session_state (dict[str, Any] | None): Initial state to inject into each session.
            existing_session_id (str | None): Session ID for get-or-create semantics.
            timeout_seconds (int): Maximum execution time per attempt.

        Returns:
            Tuple of (session, events, timed_out, error_message, attempts).
            ``session`` is None only when every session creation failed.

        Raises:
            Exception: A non-transient error from session creation is
                re-raised unchanged.
            AssertionError: If the loop ends without an attempt, which
                ``RetryPolicy`` validation rules out.

        Notes:
            A transient error is retried under ``self.retry_policy`` with a
            growing backoff. A non-transient run error, a timeout, and a
            transient error on the last attempt end the loop and are
            reported through the returned tuple.
        """
        backoff = float(self.retry_policy.backoff_seconds)
        session: Session | None = None
        attempt = 0
        for attempt in range(1, self.retry_policy.max_attempts + 1):
            session = None
            try:
                session = await self._open_session(
                    user_id, session_state, existing_session_id
                )
                events, timed_out = await self._execute_with_timeout(
                    runner, session, user_id, input_text, timeout_seconds, input_content
                )
            except Exception as e:
                if await self._retry_after(e, attempt, backoff, session):
                    backoff *= self.retry_policy.backoff_multiplier
                    continue
                if session is None and not is_transient_session_error(e):
                    raise
                self._logger.error(  # noqa: TRY400  # failure is returned in the result, not raised
                    "execution.error",
                    session_id=session.id if session else None,
                    error=str(e),
                    attempts=attempt,
                )
                return session, [], False, str(e), attempt
            else:
                return session, events, timed_out, None, attempt
        # RetryPolicy validation guarantees at least one attempt above
        raise AssertionError("_run_with_retry ended without an attempt")

    async def execute_agent(  # noqa: PLR0913  # implements the AgentExecutorProtocol signature
        self,
        agent: Any,
        input_text: str,
        *,
        input_content: types.Content | None = None,
        instruction_override: str | None = None,
        output_schema_override: Any | None = None,
        session_state: dict[str, Any] | None = None,
        existing_session_id: str | None = None,
        timeout_seconds: int = 300,
    ) -> ExecutionResult:
        """Execute an agent and return structured result.

        Runs the specified agent with the given input, optionally applying
        instruction or schema overrides for evolution scenarios. Manages
        session lifecycle and captures execution events.

        Args:
            agent (Any): ADK LlmAgent to execute. The agent's tools, output_key,
                and other ADK features are preserved during execution.
            input_text (str): User message to send to the agent. Used when
                input_content is None for backward compatibility.
            input_content (types.Content | None): Pre-assembled multimodal Content for the agent.
                When provided, takes precedence over input_text. Use this
                for multimodal inputs containing video or other media.
            instruction_override (str | None): If provided, replaces the agent's instruction
                for this execution only. Original agent is not modified.
            output_schema_override (Any | None): If provided, replaces the agent's output
                schema for this execution only (type[BaseModel]). Used for schema evolution.
            session_state (dict[str, Any] | None): Initial state to inject into the
                session. Used for template variable substitution (e.g.,
                {component_text}).
            existing_session_id (str | None): If provided, uses get-or-create semantics to
                retrieve or create a session with this ID. Enables session sharing
                between agents (e.g., critic accessing generator state).
            timeout_seconds (int): Maximum execution time in seconds. Defaults to 300.
                Execution terminates with TIMEOUT status if exceeded.

        Returns:
            ExecutionResult with status, output, and debugging information.

        Examples:
            Basic execution:

            ```python
            result = await executor.execute_agent(
                agent=greeter,
                input_text="Hello!",
            )
            print(result.extracted_value)
            ```

            With session state for reflection:

            ```python
            result = await executor.execute_agent(
                agent=reflector,
                input_text="Improve the instruction",
                session_state={
                    "component_text": "Be helpful.",
                    "trials": '[{"score": 0.5}]',
                },
            )
            ```

            With multimodal content:

            ```python
            from google.genai.types import Content, Part

            content = Content(
                role="user",
                parts=[Part(text="Describe this video"), video_part],
            )
            result = await executor.execute_agent(
                agent=analyzer,
                input_text="",  # Can be empty when content provided
                input_content=content,
            )
            ```

        Notes:
            Optional typing (Any) is used for agent parameter to avoid
            coupling to ADK types in the ports layer. Implementations
            should validate that the agent is a valid LlmAgent.

            A transient session-service error (``database is locked``) in
            session creation or the run is retried under
            ``self.retry_policy``, each attempt in a fresh session unless
            ``existing_session_id`` is given. The session of a failed
            attempt stays in the store. Timeouts and other errors are not
            retried. When every session creation fails on a lock, the
            result is FAILED with an empty ``session_id``.
        """
        start_time = time.perf_counter()
        user_id = "exec_user"
        is_multimodal = input_content is not None

        self._logger.info(
            "execution.start",
            agent_name=getattr(agent, "name", "unknown"),
            input_length=len(input_text),
            is_multimodal=is_multimodal,
            has_instruction_override=instruction_override is not None,
            has_schema_override=output_schema_override is not None,
            has_session_state=session_state is not None,
            existing_session_id=existing_session_id,
            timeout_seconds=timeout_seconds,
        )

        # Apply overrides if provided
        effective_agent = self._apply_overrides(
            agent, instruction_override, output_schema_override
        )

        # Create runner
        runner = Runner(
            agent=effective_agent,
            app_name=self._app_name,
            session_service=self._session_service,
        )

        # Open a session and execute with timeout, retrying transient errors
        (
            session,
            events,
            timed_out,
            error_message,
            attempts,
        ) = await self._run_with_retry(
            runner,
            user_id,
            input_text,
            input_content,
            session_state,
            existing_session_id,
            timeout_seconds,
        )
        session_id = session.id if session else ""

        # Calculate execution time
        execution_time = time.perf_counter() - start_time

        # Determine status
        if error_message:
            status = ExecutionStatus.FAILED
        elif timed_out:
            status = ExecutionStatus.TIMEOUT
            error_message = f"Execution timed out after {timeout_seconds}s"
        else:
            status = ExecutionStatus.SUCCESS

        # Extract output (even on timeout, we try to get partial results)
        extracted_value: str | None = None
        if session and (status == ExecutionStatus.SUCCESS or (timed_out and events)):
            extracted_value = await self._extract_output(session, events, agent)

        self._logger.info(
            "execution.complete",
            session_id=session_id,
            status=status.value,
            attempts=attempts,
            execution_time_seconds=execution_time,
            events_captured=len(events),
            has_output=extracted_value is not None,
        )

        return ExecutionResult(
            status=status,
            session_id=session_id,
            extracted_value=extracted_value,
            error_message=error_message,
            execution_time_seconds=execution_time,
            captured_events=events,
        )

__init__

__init__(
    session_service: BaseSessionService | None = None,
    app_name: str = "gepa_executor",
    retry_policy: RetryPolicy | None = None,
) -> None

Initialize AgentExecutor.

PARAMETER DESCRIPTION
session_service

ADK session service for state management. If None, creates an InMemorySessionService.

TYPE: BaseSessionService | None DEFAULT: None

app_name

Application name for ADK runner. Defaults to "gepa_executor".

TYPE: str DEFAULT: 'gepa_executor'

retry_policy

Policy for retrying a transient session-service error. If None, uses RetryPolicy() (three attempts, 0.5 s backoff, doubling).

TYPE: RetryPolicy | None DEFAULT: None

Examples:

Default initialization:

executor = AgentExecutor()

With custom app name:

executor = AgentExecutor(app_name="my_app")

With a custom retry policy:

executor = AgentExecutor(
    session_service=sqlite_service,
    retry_policy=RetryPolicy(max_attempts=5),
)
Notes

Creates a shared executor that uses the session service for all agent executions, allowing session state to be shared between executions when desired.

Source code in src/gepa_adk/adapters/execution/agent_executor.py
def __init__(
    self,
    session_service: BaseSessionService | None = None,
    app_name: str = "gepa_executor",
    retry_policy: RetryPolicy | None = None,
) -> None:
    """Initialize AgentExecutor.

    Args:
        session_service: ADK session service for state management.
            If None, creates an InMemorySessionService.
        app_name: Application name for ADK runner. Defaults to "gepa_executor".
        retry_policy: Policy for retrying a transient session-service
            error. If None, uses ``RetryPolicy()`` (three attempts,
            0.5 s backoff, doubling).

    Examples:
        Default initialization:

        ```python
        executor = AgentExecutor()
        ```

        With custom app name:

        ```python
        executor = AgentExecutor(app_name="my_app")
        ```

        With a custom retry policy:

        ```python
        executor = AgentExecutor(
            session_service=sqlite_service,
            retry_policy=RetryPolicy(max_attempts=5),
        )
        ```

    Notes:
        Creates a shared executor that uses the session service for all
        agent executions, allowing session state to be shared between
        executions when desired.
    """
    self._session_service = session_service or InMemorySessionService()
    self._app_name = app_name
    self.retry_policy = retry_policy or RetryPolicy()
    self._logger = logger.bind(component="AgentExecutor", app_name=app_name)

execute_agent async

execute_agent(
    agent: Any,
    input_text: str,
    *,
    input_content: Content | None = None,
    instruction_override: str | None = None,
    output_schema_override: Any | None = None,
    session_state: dict[str, Any] | None = None,
    existing_session_id: str | None = None,
    timeout_seconds: int = 300,
) -> ExecutionResult

Execute an agent and return structured result.

Runs the specified agent with the given input, optionally applying instruction or schema overrides for evolution scenarios. Manages session lifecycle and captures execution events.

PARAMETER DESCRIPTION
agent

ADK LlmAgent to execute. The agent's tools, output_key, and other ADK features are preserved during execution.

TYPE: Any

input_text

User message to send to the agent. Used when input_content is None for backward compatibility.

TYPE: str

input_content

Pre-assembled multimodal Content for the agent. When provided, takes precedence over input_text. Use this for multimodal inputs containing video or other media.

TYPE: Content | None DEFAULT: None

instruction_override

If provided, replaces the agent's instruction for this execution only. Original agent is not modified.

TYPE: str | None DEFAULT: None

output_schema_override

If provided, replaces the agent's output schema for this execution only (type[BaseModel]). Used for schema evolution.

TYPE: Any | None DEFAULT: None

session_state

Initial state to inject into the session. Used for template variable substitution (e.g., {component_text}).

TYPE: dict[str, Any] | None DEFAULT: None

existing_session_id

If provided, uses get-or-create semantics to retrieve or create a session with this ID. Enables session sharing between agents (e.g., critic accessing generator state).

TYPE: str | None DEFAULT: None

timeout_seconds

Maximum execution time in seconds. Defaults to 300. Execution terminates with TIMEOUT status if exceeded.

TYPE: int DEFAULT: 300

RETURNS DESCRIPTION
ExecutionResult

ExecutionResult with status, output, and debugging information.

Examples:

Basic execution:

result = await executor.execute_agent(
    agent=greeter,
    input_text="Hello!",
)
print(result.extracted_value)

With session state for reflection:

result = await executor.execute_agent(
    agent=reflector,
    input_text="Improve the instruction",
    session_state={
        "component_text": "Be helpful.",
        "trials": '[{"score": 0.5}]',
    },
)

With multimodal content:

from google.genai.types import Content, Part

content = Content(
    role="user",
    parts=[Part(text="Describe this video"), video_part],
)
result = await executor.execute_agent(
    agent=analyzer,
    input_text="",  # Can be empty when content provided
    input_content=content,
)
Notes

Optional typing (Any) is used for agent parameter to avoid coupling to ADK types in the ports layer. Implementations should validate that the agent is a valid LlmAgent.

A transient session-service error (database is locked) in session creation or the run is retried under self.retry_policy, each attempt in a fresh session unless existing_session_id is given. The session of a failed attempt stays in the store. Timeouts and other errors are not retried. When every session creation fails on a lock, the result is FAILED with an empty session_id.

Source code in src/gepa_adk/adapters/execution/agent_executor.py
async def execute_agent(  # noqa: PLR0913  # implements the AgentExecutorProtocol signature
    self,
    agent: Any,
    input_text: str,
    *,
    input_content: types.Content | None = None,
    instruction_override: str | None = None,
    output_schema_override: Any | None = None,
    session_state: dict[str, Any] | None = None,
    existing_session_id: str | None = None,
    timeout_seconds: int = 300,
) -> ExecutionResult:
    """Execute an agent and return structured result.

    Runs the specified agent with the given input, optionally applying
    instruction or schema overrides for evolution scenarios. Manages
    session lifecycle and captures execution events.

    Args:
        agent (Any): ADK LlmAgent to execute. The agent's tools, output_key,
            and other ADK features are preserved during execution.
        input_text (str): User message to send to the agent. Used when
            input_content is None for backward compatibility.
        input_content (types.Content | None): Pre-assembled multimodal Content for the agent.
            When provided, takes precedence over input_text. Use this
            for multimodal inputs containing video or other media.
        instruction_override (str | None): If provided, replaces the agent's instruction
            for this execution only. Original agent is not modified.
        output_schema_override (Any | None): If provided, replaces the agent's output
            schema for this execution only (type[BaseModel]). Used for schema evolution.
        session_state (dict[str, Any] | None): Initial state to inject into the
            session. Used for template variable substitution (e.g.,
            {component_text}).
        existing_session_id (str | None): If provided, uses get-or-create semantics to
            retrieve or create a session with this ID. Enables session sharing
            between agents (e.g., critic accessing generator state).
        timeout_seconds (int): Maximum execution time in seconds. Defaults to 300.
            Execution terminates with TIMEOUT status if exceeded.

    Returns:
        ExecutionResult with status, output, and debugging information.

    Examples:
        Basic execution:

        ```python
        result = await executor.execute_agent(
            agent=greeter,
            input_text="Hello!",
        )
        print(result.extracted_value)
        ```

        With session state for reflection:

        ```python
        result = await executor.execute_agent(
            agent=reflector,
            input_text="Improve the instruction",
            session_state={
                "component_text": "Be helpful.",
                "trials": '[{"score": 0.5}]',
            },
        )
        ```

        With multimodal content:

        ```python
        from google.genai.types import Content, Part

        content = Content(
            role="user",
            parts=[Part(text="Describe this video"), video_part],
        )
        result = await executor.execute_agent(
            agent=analyzer,
            input_text="",  # Can be empty when content provided
            input_content=content,
        )
        ```

    Notes:
        Optional typing (Any) is used for agent parameter to avoid
        coupling to ADK types in the ports layer. Implementations
        should validate that the agent is a valid LlmAgent.

        A transient session-service error (``database is locked``) in
        session creation or the run is retried under
        ``self.retry_policy``, each attempt in a fresh session unless
        ``existing_session_id`` is given. The session of a failed
        attempt stays in the store. Timeouts and other errors are not
        retried. When every session creation fails on a lock, the
        result is FAILED with an empty ``session_id``.
    """
    start_time = time.perf_counter()
    user_id = "exec_user"
    is_multimodal = input_content is not None

    self._logger.info(
        "execution.start",
        agent_name=getattr(agent, "name", "unknown"),
        input_length=len(input_text),
        is_multimodal=is_multimodal,
        has_instruction_override=instruction_override is not None,
        has_schema_override=output_schema_override is not None,
        has_session_state=session_state is not None,
        existing_session_id=existing_session_id,
        timeout_seconds=timeout_seconds,
    )

    # Apply overrides if provided
    effective_agent = self._apply_overrides(
        agent, instruction_override, output_schema_override
    )

    # Create runner
    runner = Runner(
        agent=effective_agent,
        app_name=self._app_name,
        session_service=self._session_service,
    )

    # Open a session and execute with timeout, retrying transient errors
    (
        session,
        events,
        timed_out,
        error_message,
        attempts,
    ) = await self._run_with_retry(
        runner,
        user_id,
        input_text,
        input_content,
        session_state,
        existing_session_id,
        timeout_seconds,
    )
    session_id = session.id if session else ""

    # Calculate execution time
    execution_time = time.perf_counter() - start_time

    # Determine status
    if error_message:
        status = ExecutionStatus.FAILED
    elif timed_out:
        status = ExecutionStatus.TIMEOUT
        error_message = f"Execution timed out after {timeout_seconds}s"
    else:
        status = ExecutionStatus.SUCCESS

    # Extract output (even on timeout, we try to get partial results)
    extracted_value: str | None = None
    if session and (status == ExecutionStatus.SUCCESS or (timed_out and events)):
        extracted_value = await self._extract_output(session, events, agent)

    self._logger.info(
        "execution.complete",
        session_id=session_id,
        status=status.value,
        attempts=attempts,
        execution_time_seconds=execution_time,
        events_captured=len(events),
        has_output=extracted_value is not None,
    )

    return ExecutionResult(
        status=status,
        session_id=session_id,
        extracted_value=extracted_value,
        error_message=error_message,
        execution_time_seconds=execution_time,
        captured_events=events,
    )

SessionNotFoundError

Bases: EvolutionError


              flowchart TD
              gepa_adk.adapters.execution.SessionNotFoundError[SessionNotFoundError]
              gepa_adk.domain.exceptions.EvolutionError[EvolutionError]

                              gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.adapters.execution.SessionNotFoundError
                


              click gepa_adk.adapters.execution.SessionNotFoundError href "" "gepa_adk.adapters.execution.SessionNotFoundError"
              click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
            

Raised when a requested session does not exist.

ATTRIBUTE DESCRIPTION
session_id

The session ID that was not found.

TYPE: str

Examples:

Handling session not found with strict existence checking:

from gepa_adk.adapters.execution.agent_executor import SessionNotFoundError

try:
    session = await executor._get_session(
        session_id="invalid_session",
        user_id="user_123",
    )
except SessionNotFoundError as e:
    print(f"Session not found: {e.session_id}")
Notes

Arises only from strict existence-checking paths like _get_session(). The execute_agent() method uses get-or-create semantics and will not raise this exception.

Source code in src/gepa_adk/adapters/execution/agent_executor.py
class SessionNotFoundError(EvolutionError):
    """Raised when a requested session does not exist.

    Attributes:
        session_id (str): The session ID that was not found.

    Examples:
        Handling session not found with strict existence checking:

        ```python
        from gepa_adk.adapters.execution.agent_executor import SessionNotFoundError

        try:
            session = await executor._get_session(
                session_id="invalid_session",
                user_id="user_123",
            )
        except SessionNotFoundError as e:
            print(f"Session not found: {e.session_id}")
        ```

    Notes:
        Arises only from strict existence-checking paths like _get_session().
        The execute_agent() method uses get-or-create semantics and will not
        raise this exception.
    """

    def __init__(self, session_id: str) -> None:
        """Initialize SessionNotFoundError.

        Args:
            session_id: The session ID that was not found.
        """
        self.session_id = session_id
        super().__init__(f"Session not found: {session_id}")

__init__

__init__(session_id: str) -> None

Initialize SessionNotFoundError.

PARAMETER DESCRIPTION
session_id

The session ID that was not found.

TYPE: str

Source code in src/gepa_adk/adapters/execution/agent_executor.py
def __init__(self, session_id: str) -> None:
    """Initialize SessionNotFoundError.

    Args:
        session_id: The session ID that was not found.
    """
    self.session_id = session_id
    super().__init__(f"Session not found: {session_id}")

TrialBuilder

Build trial records for reflection datasets.

Constructs consistent trial structures following the GEPA whitepaper format. Extracts feedback fields from scorer metadata and builds trajectory dicts.

ATTRIBUTE DESCRIPTION
_logger

Logger for metadata passthrough debugging.

TYPE: BoundLogger

Examples:

Basic trial building:

builder = TrialBuilder()

# With minimal data
trial = builder.build_trial(
    input_text="Hello",
    output="Hi there!",
    score=0.8,
)

# With full metadata
trial = builder.build_trial(
    input_text="Explain AI",
    output="AI is...",
    score=0.9,
    metadata={
        "feedback": "Clear explanation",
        "dimension_scores": {"clarity": 0.95},
        "actionable_guidance": "Add examples",
    },
    extra_trajectory={"component": "instruction"},
)
See Also
Notes

All optional metadata fields are validated before inclusion to prevent malformed data from propagating to reflection prompts.

Source code in src/gepa_adk/adapters/execution/trial_builder.py
class TrialBuilder:
    """Build trial records for reflection datasets.

    Constructs consistent trial structures following the GEPA whitepaper format.
    Extracts feedback fields from scorer metadata and builds trajectory dicts.

    Attributes:
        _logger (structlog.BoundLogger): Logger for metadata passthrough debugging.

    Examples:
        Basic trial building:

        ```python
        builder = TrialBuilder()

        # With minimal data
        trial = builder.build_trial(
            input_text="Hello",
            output="Hi there!",
            score=0.8,
        )

        # With full metadata
        trial = builder.build_trial(
            input_text="Explain AI",
            output="AI is...",
            score=0.9,
            metadata={
                "feedback": "Clear explanation",
                "dimension_scores": {"clarity": 0.95},
                "actionable_guidance": "Add examples",
            },
            extra_trajectory={"component": "instruction"},
        )
        ```

    See Also:
        - [`build_feedback`][gepa_adk.adapters.execution.trial_builder.TrialBuilder.build_feedback]:
          Build just the feedback dict.

    Notes:
        All optional metadata fields are validated before inclusion to prevent
        malformed data from propagating to reflection prompts.
    """

    def __init__(self) -> None:
        """Initialize the TrialBuilder.

        Examples:
            ```python
            builder = TrialBuilder()
            ```

        Notes:
            Creates a module-scoped logger for metadata passthrough debugging.
        """
        self._logger = structlog.get_logger(__name__)

    def build_feedback(
        self,
        score: float,
        metadata: dict[str, Any] | None = None,
        *,
        error: str | None = None,
        log_passthrough: bool = False,
    ) -> dict[str, Any]:
        """Build the feedback dict from score and metadata.

        Extracts and validates feedback fields from scorer metadata, including
        feedback_text, feedback_guidance, and feedback_dimensions.

        Args:
            score: Evaluation score (mandatory).
            metadata: Optional scorer metadata dict containing:
                - feedback: Text feedback from critic.
                - actionable_guidance: Improvement suggestions.
                - dimension_scores: Per-dimension score breakdown.
            error: Optional error message to include in feedback.
            log_passthrough: If True, log debug info about metadata extraction.

        Returns:
            Feedback dict with keys:
                - score (mandatory): The evaluation score.
                - feedback_text (if available): Text feedback from critic.
                - feedback_guidance (if available): Improvement suggestions.
                - feedback_dimensions (if available): Dimension score breakdown.
                - error (if provided): Error message from execution.

        Examples:
            ```python
            builder = TrialBuilder()

            # Minimal feedback
            feedback = builder.build_feedback(0.75)
            assert feedback == {"score": 0.75}

            # With metadata
            feedback = builder.build_feedback(
                0.85,
                metadata={
                    "feedback": "Good work",
                    "dimension_scores": {"accuracy": 0.9},
                },
            )
            assert "feedback_text" in feedback
            ```

        Notes:
            Only non-empty strings and dicts are included to keep feedback clean.
        """
        # Use normalize_feedback for consistent field mapping
        feedback = normalize_feedback(score, metadata)

        # Log metadata passthrough for debugging if requested
        if log_passthrough and metadata and isinstance(metadata, dict):
            has_feedback = bool(
                metadata.get("feedback") or metadata.get("feedback_text")
            )
            has_guidance = bool(metadata.get("actionable_guidance"))
            has_dimensions = bool(metadata.get("dimension_scores"))
            self._logger.debug(
                "trial_builder.metadata.passthrough",
                has_feedback=has_feedback,
                has_guidance=has_guidance,
                has_dimensions=has_dimensions,
            )

        # Add error if present
        if error:
            feedback["error"] = error

        return feedback

    def build_trial(  # noqa: PLR0913  # optional trial fields are keyword-only
        self,
        input_text: str | None,
        output: str,
        score: float,
        metadata: dict[str, Any] | None = None,
        *,
        error: str | None = None,
        trace: dict[str, Any] | None = None,
        extra_trajectory: dict[str, Any] | None = None,
        log_passthrough: bool = False,
    ) -> dict[str, Any]:
        """Build a complete trial record for reflection.

        Constructs a trial with feedback and trajectory dicts following the
        GEPA whitepaper structure.

        Args:
            input_text (str | None): The input that was given to the system.
                Can be None for pipelines where input context is implicit.
            output (str): What the system produced.
            score (float): Evaluation score for this output.
            metadata (dict[str, Any] | None): Optional scorer metadata dict
                (from CriticScorer).
            error (str | None): Optional error message from execution.
            trace (dict[str, Any] | None): Optional execution trace dict
                (tool calls, state, tokens).
            extra_trajectory (dict[str, Any] | None): Optional extra fields to
                include in trajectory (e.g., component name, value, tokens).
            log_passthrough (bool): If True, log debug info about metadata
                extraction.

        Returns:
            Trial dict with keys:
                - feedback: Evaluation feedback (score, feedback_text, etc.)
                - trajectory: Execution journey (input, output, trace, etc.)

        Examples:
            ```python
            builder = TrialBuilder()

            # Simple trial
            trial = builder.build_trial(
                input_text="What is Python?",
                output="A programming language",
                score=0.9,
            )
            assert trial["feedback"]["score"] == 0.9
            assert trial["trajectory"]["output"] == "A programming language"

            # With trace and extra trajectory data
            trial = builder.build_trial(
                input_text="Count to 3",
                output="1, 2, 3",
                score=1.0,
                trace={"tool_calls": [{"name": "count"}]},
                extra_trajectory={"component": "counter"},
            )
            assert "trace" in trial["trajectory"]
            assert trial["trajectory"]["component"] == "counter"
            ```

        Notes:
            Optional input is only included in trajectory when not None,
            supporting pipelines where input context is implicit.
        """
        # Build feedback dict
        feedback = self.build_feedback(
            score,
            metadata,
            error=error,
            log_passthrough=log_passthrough,
        )

        # Build trajectory dict
        trajectory: dict[str, Any] = {"output": output}

        # Add input if available
        if input_text is not None:
            trajectory["input"] = input_text

        # Add trace if available
        if trace:
            trajectory["trace"] = trace

        # Add extra trajectory fields if provided
        if extra_trajectory:
            trajectory.update(extra_trajectory)

        # Build trial record
        return {
            "feedback": feedback,
            "trajectory": trajectory,
        }

__init__

__init__() -> None

Initialize the TrialBuilder.

Examples:

builder = TrialBuilder()
Notes

Creates a module-scoped logger for metadata passthrough debugging.

Source code in src/gepa_adk/adapters/execution/trial_builder.py
def __init__(self) -> None:
    """Initialize the TrialBuilder.

    Examples:
        ```python
        builder = TrialBuilder()
        ```

    Notes:
        Creates a module-scoped logger for metadata passthrough debugging.
    """
    self._logger = structlog.get_logger(__name__)

build_feedback

build_feedback(
    score: float,
    metadata: dict[str, Any] | None = None,
    *,
    error: str | None = None,
    log_passthrough: bool = False,
) -> dict[str, Any]

Build the feedback dict from score and metadata.

Extracts and validates feedback fields from scorer metadata, including feedback_text, feedback_guidance, and feedback_dimensions.

PARAMETER DESCRIPTION
score

Evaluation score (mandatory).

TYPE: float

metadata

Optional scorer metadata dict containing: - feedback: Text feedback from critic. - actionable_guidance: Improvement suggestions. - dimension_scores: Per-dimension score breakdown.

TYPE: dict[str, Any] | None DEFAULT: None

error

Optional error message to include in feedback.

TYPE: str | None DEFAULT: None

log_passthrough

If True, log debug info about metadata extraction.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
dict[str, Any]

Feedback dict with keys: - score (mandatory): The evaluation score. - feedback_text (if available): Text feedback from critic. - feedback_guidance (if available): Improvement suggestions. - feedback_dimensions (if available): Dimension score breakdown. - error (if provided): Error message from execution.

Examples:

builder = TrialBuilder()

# Minimal feedback
feedback = builder.build_feedback(0.75)
assert feedback == {"score": 0.75}

# With metadata
feedback = builder.build_feedback(
    0.85,
    metadata={
        "feedback": "Good work",
        "dimension_scores": {"accuracy": 0.9},
    },
)
assert "feedback_text" in feedback
Notes

Only non-empty strings and dicts are included to keep feedback clean.

Source code in src/gepa_adk/adapters/execution/trial_builder.py
def build_feedback(
    self,
    score: float,
    metadata: dict[str, Any] | None = None,
    *,
    error: str | None = None,
    log_passthrough: bool = False,
) -> dict[str, Any]:
    """Build the feedback dict from score and metadata.

    Extracts and validates feedback fields from scorer metadata, including
    feedback_text, feedback_guidance, and feedback_dimensions.

    Args:
        score: Evaluation score (mandatory).
        metadata: Optional scorer metadata dict containing:
            - feedback: Text feedback from critic.
            - actionable_guidance: Improvement suggestions.
            - dimension_scores: Per-dimension score breakdown.
        error: Optional error message to include in feedback.
        log_passthrough: If True, log debug info about metadata extraction.

    Returns:
        Feedback dict with keys:
            - score (mandatory): The evaluation score.
            - feedback_text (if available): Text feedback from critic.
            - feedback_guidance (if available): Improvement suggestions.
            - feedback_dimensions (if available): Dimension score breakdown.
            - error (if provided): Error message from execution.

    Examples:
        ```python
        builder = TrialBuilder()

        # Minimal feedback
        feedback = builder.build_feedback(0.75)
        assert feedback == {"score": 0.75}

        # With metadata
        feedback = builder.build_feedback(
            0.85,
            metadata={
                "feedback": "Good work",
                "dimension_scores": {"accuracy": 0.9},
            },
        )
        assert "feedback_text" in feedback
        ```

    Notes:
        Only non-empty strings and dicts are included to keep feedback clean.
    """
    # Use normalize_feedback for consistent field mapping
    feedback = normalize_feedback(score, metadata)

    # Log metadata passthrough for debugging if requested
    if log_passthrough and metadata and isinstance(metadata, dict):
        has_feedback = bool(
            metadata.get("feedback") or metadata.get("feedback_text")
        )
        has_guidance = bool(metadata.get("actionable_guidance"))
        has_dimensions = bool(metadata.get("dimension_scores"))
        self._logger.debug(
            "trial_builder.metadata.passthrough",
            has_feedback=has_feedback,
            has_guidance=has_guidance,
            has_dimensions=has_dimensions,
        )

    # Add error if present
    if error:
        feedback["error"] = error

    return feedback

build_trial

build_trial(
    input_text: str | None,
    output: str,
    score: float,
    metadata: dict[str, Any] | None = None,
    *,
    error: str | None = None,
    trace: dict[str, Any] | None = None,
    extra_trajectory: dict[str, Any] | None = None,
    log_passthrough: bool = False,
) -> dict[str, Any]

Build a complete trial record for reflection.

Constructs a trial with feedback and trajectory dicts following the GEPA whitepaper structure.

PARAMETER DESCRIPTION
input_text

The input that was given to the system. Can be None for pipelines where input context is implicit.

TYPE: str | None

output

What the system produced.

TYPE: str

score

Evaluation score for this output.

TYPE: float

metadata

Optional scorer metadata dict (from CriticScorer).

TYPE: dict[str, Any] | None DEFAULT: None

error

Optional error message from execution.

TYPE: str | None DEFAULT: None

trace

Optional execution trace dict (tool calls, state, tokens).

TYPE: dict[str, Any] | None DEFAULT: None

extra_trajectory

Optional extra fields to include in trajectory (e.g., component name, value, tokens).

TYPE: dict[str, Any] | None DEFAULT: None

log_passthrough

If True, log debug info about metadata extraction.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
dict[str, Any]

Trial dict with keys: - feedback: Evaluation feedback (score, feedback_text, etc.) - trajectory: Execution journey (input, output, trace, etc.)

Examples:

builder = TrialBuilder()

# Simple trial
trial = builder.build_trial(
    input_text="What is Python?",
    output="A programming language",
    score=0.9,
)
assert trial["feedback"]["score"] == 0.9
assert trial["trajectory"]["output"] == "A programming language"

# With trace and extra trajectory data
trial = builder.build_trial(
    input_text="Count to 3",
    output="1, 2, 3",
    score=1.0,
    trace={"tool_calls": [{"name": "count"}]},
    extra_trajectory={"component": "counter"},
)
assert "trace" in trial["trajectory"]
assert trial["trajectory"]["component"] == "counter"
Notes

Optional input is only included in trajectory when not None, supporting pipelines where input context is implicit.

Source code in src/gepa_adk/adapters/execution/trial_builder.py
def build_trial(  # noqa: PLR0913  # optional trial fields are keyword-only
    self,
    input_text: str | None,
    output: str,
    score: float,
    metadata: dict[str, Any] | None = None,
    *,
    error: str | None = None,
    trace: dict[str, Any] | None = None,
    extra_trajectory: dict[str, Any] | None = None,
    log_passthrough: bool = False,
) -> dict[str, Any]:
    """Build a complete trial record for reflection.

    Constructs a trial with feedback and trajectory dicts following the
    GEPA whitepaper structure.

    Args:
        input_text (str | None): The input that was given to the system.
            Can be None for pipelines where input context is implicit.
        output (str): What the system produced.
        score (float): Evaluation score for this output.
        metadata (dict[str, Any] | None): Optional scorer metadata dict
            (from CriticScorer).
        error (str | None): Optional error message from execution.
        trace (dict[str, Any] | None): Optional execution trace dict
            (tool calls, state, tokens).
        extra_trajectory (dict[str, Any] | None): Optional extra fields to
            include in trajectory (e.g., component name, value, tokens).
        log_passthrough (bool): If True, log debug info about metadata
            extraction.

    Returns:
        Trial dict with keys:
            - feedback: Evaluation feedback (score, feedback_text, etc.)
            - trajectory: Execution journey (input, output, trace, etc.)

    Examples:
        ```python
        builder = TrialBuilder()

        # Simple trial
        trial = builder.build_trial(
            input_text="What is Python?",
            output="A programming language",
            score=0.9,
        )
        assert trial["feedback"]["score"] == 0.9
        assert trial["trajectory"]["output"] == "A programming language"

        # With trace and extra trajectory data
        trial = builder.build_trial(
            input_text="Count to 3",
            output="1, 2, 3",
            score=1.0,
            trace={"tool_calls": [{"name": "count"}]},
            extra_trajectory={"component": "counter"},
        )
        assert "trace" in trial["trajectory"]
        assert trial["trajectory"]["component"] == "counter"
        ```

    Notes:
        Optional input is only included in trajectory when not None,
        supporting pipelines where input context is implicit.
    """
    # Build feedback dict
    feedback = self.build_feedback(
        score,
        metadata,
        error=error,
        log_passthrough=log_passthrough,
    )

    # Build trajectory dict
    trajectory: dict[str, Any] = {"output": output}

    # Add input if available
    if input_text is not None:
        trajectory["input"] = input_text

    # Add trace if available
    if trace:
        trajectory["trace"] = trace

    # Add extra trajectory fields if provided
    if extra_trajectory:
        trajectory.update(extra_trajectory)

    # Build trial record
    return {
        "feedback": feedback,
        "trajectory": trajectory,
    }