AlphaEvolve API reference

This document serves as the authoritative, production-grade API reference and system specification for the AlphaEvolve Cloud API under the Google Cloud Discovery Engine conversational layers. It defines the precise nested resource hierarchies, REST and gRPC endpoints, field-level constraints, lifecycle state machines, error diagnostic matrixes, security sandboxing rules, and integration workflows necessary to engineer a fully automated client-side controller and evaluation loop.

Unified lifecycle state machines

The AlphaEvolve agent coordinates two independent state machines to monitor experiment campaign progression and manage the delivery and execution of individual program mutations.

Experiment lifecycle states

An experiment represents the overall optimization campaign. It is processed as a persistent server-side resource and transitions through the following states:

  • CREATED: The initialization state. The resource is declared and configured but has not yet populated initial generations or dispatched API calls.

  • RUNNING: The active evaluation state. The engine is concurrently sampling parent candidates, generating code mutations through the LLM mixture, and streaming tasks to evaluators.

  • PAUSED: A temporary holding state triggered manually or through an automated protective idle_timeout. Code generation stops, and existing workers pause metric delivery.

  • COMPLETED: A terminal state indicating that the search has successfully fulfilled its max_programs target allocation or reached its structural generation limit.

  • FAILED: A terminal error state indicating that systemic environment issues—such as uncaught API credential exceptions, data store corruption, or consecutive runner panics—halted processing execution.

Program states

The runtime validation sequence is applied to individual candidate variants.

Every generated code mutation behaves as an isolated program entity that transitions through a sequence of granular operational states within the population database.

  1. INITIALIZED: The program entry is created in the database, tracking its ancestral pedigree and parent program linkages.

  2. GENERATING: A task is actively dispatched to the language model mixture backend to draft or mutate the specific functional code blocks.

  3. EVALUATING: The code payload is locked by an evaluation worker process and executed inside an isolated test harness environment.

  4. COMPLETED: The execution scores and descriptive structural insights are safely committed to the evolutionary database, and the program is added to the selection pool.

Concurrency and locking mechanics

Programs are acquired by worker loops using an atomic lock token mechanism to prevent race conditions or duplicate scoring overhead across distributed topologies. The evaluator must submit the finalized scoring schema alongside the exact matching lock token to successfully commit results back to the database.

Configuration and settings schemas

Overview of the core schema configurations, parameters, and defaults utilized by the AlphaEvolve engine runtime.

AlphaEvolveExperimentConfig

Defines the core structural parameters and programmatic constraints of the evolutionary experiment run.

Field Name Type Default Constraints / Value Bounds Technical Description
title string Required Max 256 characters Unique display name of the experiment.
problemDescription string Required Max 5,000 characters The formal specification of the problem. It is injected directly into prompt contexts to establish rules.
programmingLanguage string Required Freeform value Target language of the evolved codebase (for example, "python", "cpp", "verilog", "cuda", "julia", "java").
runSettings object Required Maps to RunSettings schema Pacing and timeout parameters.
generationSettings object Required Maps to GenerationSettings schema Model selection and context parameters.
evolutionSettings object Required Maps to EvolutionSettings schema Parent-selection and diversity parameters.
notes string Required Max 1,000 characters Optional annotations for run documentation.

RunSettings

Governs throughput pacing, parallelization limits, and automatic system timeouts.

Field Name Type Default Constraints / Value Bounds Technical Description
maxPrograms int32 100 Min: 1, Max: 100000 Total execution budget (programs to generate and evaluate).
concurrency int32 1 Min: 1, Max: 30 Number of parallel program mutations active in the queue. Values >30 are not allowed.
maxDuration string null ISO 8601 dayTimeDuration string
Min: >=0, Max: 7 Days
Total wall-clock time allowed before the experiment is stopped.
idleTimeout string null ISO 8601 dayTimeDuration string
Min: >=0, Max: 24 Hrs
Inactivity duration before automatic transition to `PAUSED`.

Generation settings

The GenerationSettings schema controls the prompt assembly, context windows, and model configurations for mutations:

  • context (string): Optional user-provided reference documentation, supplemental APIs, or rules. It is strictly recommended to stay under 200,000 tokens. Context sizes exceeding 200,000 tokens dilute the model's attention and degrade mutation quality.

  • includeFullProgramInPrompt (bool): Default false.

    • true: The mutation prompt includes the mutable # EVOLVE-BLOCK and the surrounding immutable boilerplate (highly recommended for complex structural reasoning).

    • false: Only the mutable block is visible, saving token context.

Evolution settings

The EvolutionSettings schema controls island-model reseeding and parent sampling probabilities:

  • parentSamplingConfigparetoSamplingConfigparetoSamplingProbability (float): The probability (0.0 to 1.0) of sampling parent programs directly from the active Pareto frontier rather than using standard fitness-based selection. This parameter must be set to 0.0 (disabled) if the optimized metrics return only a single scalar metric.

Candidate program data models

This section outlines the data schemas and representations used to define and organize candidate code structures within the population database.

AlphaEvolveProgramContent

Defines the files and structural makeup of the candidate program.

  • files (array of AlphaEvolveSourceFile): A list of all files comprising the candidate codebase. This collection is strictly capped at a maximum of 50 files per candidate program.

  • description (string): An auto-generated summary outlining the programmatic changes suggested by the generation model (Max 1,000 characters).

AlphaEvolveSourceFile

Represents an individual source code file in the codebase.

  • path (string): The workspace-relative path destination (Max 256 characters). If configuring a Python workspace, the primary executable file entry point must be named exactly "initial_program.py".

  • content (string): The raw source code string comprising the functional implementation blocks. The total cumulative codebase footprint combined across all files must be under 4,000 to 5,000 lines of code (LOC).

  • programLanguage (string): The language parser mapping tag. This string must explicitly match the language designated within the parent experiment configuration.

  • description (string): An optional summary outlining the file's individual architecture or purpose, which is exposed to the LLM during mutation passes (Max 500 characters).

AlphaEvolveProgramEvaluation

The structured payload submitted by client runner instances back to the evolutionary database following runtime execution.

  • scores (AlphaEvolveScores): Standardized, objective numerical metric values. Best practices dictate restricting this to 3 to 5 distinct float metrics; excessive target dimensions degrade multi-objective Pareto comparator performance.

  • insights (array of AlphaEvolveEvaluationInsight): Diagnostic semantic labels and natural-language execution traces passed back to assist the LLM's subsequent mutation generation attempts (Recommended maximum of 10 items).

Score formulation and ingestion formats

The maximization rule

AlphaEvolve operates fundamentally as a monotonic hill-climbing algorithm and strictly maximizes all numerical metrics. If your evaluation pipeline tracks a minimization target (such as minimizing application latency in milliseconds or reducing memory usage), you must negate the value before submitting it back to the database: submitted_score = -latency_ms.

The scores should ideally be continuous. Boolean or highly discrete metrics don't provide a sufficient gradient signal for effective hill-climbing exploration.

Single-objective ingestion schema

Use the following JSON when your evaluation harness optimizes against a single scalar objective function.

```json
{
  "scores": {
    "scores": [
      {
        "metric": "accuracy",
        "score": 0.95
      }
    ]
  },
  "insights": {
    "insights": [
      {
        "label": "validation",
        "text": "Passed syntax and basic compilation."
      }
    ]
  }
}
```

Multi-objective ingestion schema

Use the following JSON when passing independent multi-objective tracking parameters to activate server-side Pareto frontier optimization routines.

{
  "scores": {
    "scores": [
      {
        "metric": "accuracy",
        "score": 0.95
      },
      {
        "metric": "latency",
        "score": -42.5
      }
    ]
  },
  "insights": {
    "insights": [
      {
        "label": "verification",
        "text": "Passed 5 out of 5 unit tests."
      },
      {
        "label": "latency_warning",
        "text": "Latency regression of 3% observed on large dataset."
      }
    ]
  }
}

Fetching and querying program data

The AlphaEvolve system logs the telemetry, execution metrics, and full source code of every generated mutation, allowing developers to query this historical datastore using the API or CLI to track optimization progress and extract the highest-performing code candidates.

Program retrieval using REST API

Evaluated program resources can be queried from the database using the standard ListAlphaEvolvePrograms endpoint with filtering and sorting query parameters:

  • State filtering: Query programs matching a specific lifecycle state:

    GET /v1alpha/{parent}/alphaEvolvePrograms?state_filter=COMPLETED
    
  • Metric-based sorting: Retrieve sorted candidates based on optimized metrics:

    GET /v1alpha/{parent}/alphaEvolvePrograms?order_by=accuracy desc,latency&page_size=5
    

Program retrieval using CLI

To pull the top completed candidates directly from your terminal, run the following command:

ae results best <experiment-nickname> --top 5

Complete CLI usage examples

The AlphaEvolve CLI provides developers with quick administrative control and monitoring over campaigns directly from the shell:

  • List all experiments in a conversational session:

    ae experiment list
    
  • List all mutated candidate programs for a specific experiment:

    ae program list EXPERIMENT_NICKNAME \
      --state=COMPLETED \
      --order_by="accuracy desc"
    

    Replace EXPERIMENT_NICKNAME with the name of your experiment.

  • Retrieve the top-performing completed code candidates:

    ae results best EXPERIMENT_NICKNAME --top 5
    

    Replace EXPERIMENT_NICKNAME with the name of your experiment.

  • Resume a paused campaign:

    ae experiment resume EXPERIMENT_NICKNAME
    

    Replace EXPERIMENT_NICKNAME with the name of your experiment.

Core REST API endpoint directory

All endpoints are versioned under v1alpha of the Google Cloud Discovery Engine API.

Parent resource path pattern

The true nested parent resource URI is structured as: projects/{project}/locations/{location}/collections/{collection}/ engines/{engine}/sessions/{session}

Create experiment (POST)

  • Path: POST v1alpha/{parent=projects/*/locations/*/collections/*/engines/*/ sessions/*}/alphaEvolveExperiments

  • Request body: AlphaEvolveExperimentConfig (See Section 2.1)

  • Response: AlphaEvolveExperiment resource containing the initialized campaign.

  • HTTP Status: 200 OK

API payload examples

  1. Request body example (POST /alphaEvolveExperiments)

    {
      "config": {
        "title": "Sorting Optimization Campaign",
        "problemDescription": "Optimize the custom_heuristic function.",
        "programLanguage": "python",
        "notes": "Exploring convergence with Gemini 3.5 Flash.",
        "runSettings": {
          "maxPrograms": 250,
          "concurrency": 8,
          "maxDuration": "86400s",
          "idleTimeout": "1800s"
        },
        "generationSettings": {
          "context": "Ensure custom_heuristic is in-place.",
          "includeFullProgramInPrompt": true,
          "models": [
            {
              "name": "gemini-3.5-flash",
              "weight": 1.0
            }
          ]
        },
        "evolutionSettings": {
          "parentSamplingConfig": {
            "paretoSamplingConfig": {
              "paretoSamplingProbability": 0.0
            }
          }
        }
      }
    }
    
  2. Response body example (200 OK)

    {
      "name": "projects/.../sort-opt-01",
      "state": "CREATED",
      "createTime": "2026-06-23T13:30:00Z",
      "config": {
        "title": "Sorting Optimization Campaign",
        "problemDescription": "Optimize the custom_heuristic function.",
        "programLanguage": "python",
        "notes": "Exploring convergence with Gemini 3.5 Flash.",
        "runSettings": {
          "maxPrograms": 250,
          "concurrency": 8,
          "maxDuration": "86400s",
          "idleTimeout": "1800s"
        },
        "generationSettings": {
          "context": "Ensure custom_heuristic is in-place.",
          "includeFullProgramInPrompt": true,
          "models": [
            {
              "name": "gemini-3.5-flash",
              "weight": 1.0
            }
          ]
        },
        "evolutionSettings": {
          "parentSamplingConfig": {
            "paretoSamplingConfig": {
              "paretoSamplingProbability": 0.0
            }
          }
        }
      }
    }
    

Start experiment (POST)

  • Path: POST v1alpha/{name=projects/*/locations/*/collections/*/engines/*/ sessions/*/alphaEvolveExperiments/*}:start

  • Request body: StartExperimentRequest

  • Deprecation warning: The body field initialProgram is deprecated and ignored.

  • Response: GoogleLongrunningOperation (LRO).

  • HTTP status: 200 OK (Transitions state from CREATED to RUNNING)

API payload examples

  1. Request body example

    {
      "desiredProgramsCount": 1
    }
    
  2. Response body example (200 OK - long-running operation)

    {
      "name": "projects/.../operations/start-op-7788",
      "metadata": {
        "@type": "type.googleapis.com/.../AlphaEvolveStartExperimentMetadata",
        "createTime": "2026-06-23T13:31:00Z"
      },
      "done": false
    }
    

Acquire programs (POST)

  • Path: POST v1alpha/{parent=projects/*/locations/*/collections/*/engines/*/ sessions/*/alphaEvolveExperiments/*}:acquirePrograms

  • Request body: AcquireProgramsRequest

    • desiredProgramsCount (int32): Optional batch count of mutated programs to retrieve (defaults to 1 when unset).
  • Response statuses:

    • 200 OK: Returns response containing locked AlphaEvolveProgram resources.

    • 204 No Content: The queue is empty or the campaign is paused. Runners must sleep (for example, 15 seconds) and retry.

API payload examples

  1. Request body example

    {
      "desiredProgramsCount": 1
    }
    
  2. Response body example (200 OK)

    {
      "programs": [
        {
          "name": "projects/.../alphaEvolvePrograms/prog-102",
          "lockToken": "token_uuid_8877_x99",
          "state": "EVALUATING",
          "createTime": "2026-06-23T13:32:00Z",
          "content": {
            "description": "Mutated candidate program.",
            "files": [
              {
                "path": "initial_program.py",
                "programLanguage": "python",
                "description": "Primary sorting executable.",
                "content": "def custom_heuristic(arr, _):\n    ..."
              }
            ]
          }
        }
      ]
    }
    
  3. Response body example (204 No Content)

HTTP Status 204 returned with an empty payload context.

Submit programs evaluations (POST)

  • Path: POST v1alpha/{parent=projects/*/locations/*/collections/*/engines/*/ sessions/*/alphaEvolveExperiments/*}:submitProgramsEvaluations

  • Request body: SubmitProgramsEvaluationsRequest

    • evaluationSubmissions (array): Contains matching lockToken, the qualified program resource path, and the evaluation payload (scores and insights).
  • Response: SubmitProgramsEvaluationsResponse (empty).

  • HTTP status: 200 OK (Saves scores, releases active lock, and registers insights)

API payload examples

  1. Request body example

    {
      "evaluationSubmissions": [
        {
          "lockToken": "token_uuid_8877_x99",
          "program": "projects/.../alphaEvolvePrograms/prog-102",
          "evaluation": {
            "scores": {
              "scores": [
                {
                  "metric": "latency_performance",
                  "score": evaluation_payload["score"]
                }
              ]
            },
            "insights": {
              "insights": [
                {
                  "label": "benchmark",
                  "text": "Completed test case in 12.45ms."
                }
              ]
            }
          }
        }
      ]
    }
    
  2. Response body example (200 OK)

    {}
    

Resume experiment (POST)

  • Path: POST v1alpha/{name=projects/*/locations/*/collections/*/engines/*/ sessions/*/alphaEvolveExperiments/*}:resume

  • Request body: ResumeExperimentRequest

  • Response: GoogleLongrunningOperation (LRO).

  • HTTP status: 200 OK (Transitions state from PAUSED back to RUNNING)

API payload examples

  1. Request body example

    {}
    
  2. Response body example (200 OK - long-running operation)

{
  "name": "projects/.../operations/resume-op-9900",
  "metadata": {
    "@type": "type.googleapis.com/.../AlphaEvolveResumeExperimentMetadata",
    "createTime": "2026-06-23T13:45:00Z"
  },
  "done": false
}

List programs (GET)

  • Path: GET v1alpha/{parent=projects/*/locations/*/collections/*/engines/*/ sessions/*/alphaEvolveExperiments/*}/alphaEvolvePrograms

  • Query parameters:

    • stateFilter (string): Optional. Standard list filter, for example, stateFilter = 'COMPLETED'.

    • orderBy (string): Optional. Metric-based sort, for example, accuracy desc.

  • Response: ListAlphaEvolveProgramsResponse.

  • HTTP Status: 200 OK

API payload examples

  1. Request query URL example

    GET v1alpha/projects/.../alphaEvolveExperiments/sort-opt-01/
      alphaEvolvePrograms?stateFilter=COMPLETED&orderBy=latency_performance%20desc
      &pageSize=1
    
  2. Response body example (200 OK)

    {
      "alphaEvolvePrograms": [
        {
          "name": "projects/.../alphaEvolvePrograms/prog-102",
          "state": "COMPLETED",
          "createTime": "2026-06-23T13:32:00Z",
          "evaluation": {
            "scores": {
              "scores": [
                {
                  "metric": "latency_performance",
                  "score": -12.45
                }
              ]
            },
            "insights": {
              "insights": [
                {
                  "label": "benchmark",
                  "text": "Completed test case in 12.45ms."
                }
              ]
            }
          }
        }
      ],
      "nextPageToken": "token_page_1_next"
    }
    

Diagnostic code and troubleshooting reference

API diagnostic code matrix

HTTP status Error type System cause Workaround or mitigation action
400 INVALID_ARGUMENT Missing # EVOLVE-BLOCK-START / # EVOLVE-BLOCK-END comment tags; invalid JSON schema syntax; exceeded file or LOC limits. Verify block comments are placed within function bodies using valid target language syntax. Check that file count and LOC bounds are respected.
403 PERMISSION_DENIED The user or service account does not have the Discovery Engine User role or an assigned Gemini Enterprise license. Verify active Gemini Enterprise licenses. Ensure the application default credentials are properly configured for both the user and the project by running:

gcloud auth application-default login --project=<<PROJECT_ID>>

Note: Model Armor is not supported under AlphaEvolve configurations.
408 LOCK_TIMEOUT Client runner exceeded its execution duration; program lock expired on the queue. Enforce strict client-side timeouts of 30 minutes. If exceeded, immediately submit failure penalty scores to clear the queue lock.
429 RESOURCE_EXHAUSTED Exceeded active concurrent execution limits or model quotas. Implement client-side exponential backoff; configure conservative concurrency settings inside RunSettings.
503 SERVICE_UNAVAILABLE Backend service overloaded or undergoing maintenance. Implement a retry loop with randomized exponential backoff on the client side.

Remediating "silent drops"

A safety filter intercept (silent drop) occurs when server-side language models flag and drop mutated candidate prompts due to sensitive phrasing or safety rule triggers. The server silences the output, causing the queue to return empty responses, and client runners may wait indefinitely.

Workaround remediation:

  • Sanitize context: Remove emotionally charged or security-sensitive phrases from the problemDescription.

  • Filter insights: Parse and truncate raw exception traces or terminal stderr logs in the insights payload to prevent echoing unsafe system content that triggers downstream filters.

  • Localize datasets: Do not place training records or large text corpora within prompts; load them locally in the client environment during the evaluation loop execution.

Client-side evaluation best practices

The "spaghetti code" bottleneck

Suboptimal source formatting degrades optimization quality: "Spaghetti code == Noisy search space". Before placing EVOLVE-BLOCK markers:

  • Refactor code blocks so that variables and function signatures are clearly named.

  • Add descriptive, concise docstrings explaining what each function or variable does and why.

  • Ensure that any external, immutable dependencies (like importing helper modules or loading static data) live outside the # EVOLVE-BLOCK.

Context window allocation

To maximize mutation creativity, limit the code payload sent to the API. The total program context should remain under 150,000 to 200,000 tokens. Large blocks of static, immutable boilerplate consume model attention and degrade performance. Move utility scripts, data ingestion pipelines, and heavy validation libraries entirely to the client-side evaluator.

Prime the initial program first

Before running AlphaEvolve, use a standard coding agent to debug both your seed codebase and your evaluator:

  • Prime the seed: Fix obvious syntax bugs, compile issues, and edge-cases.

  • Verify the starting score: Verify that the baseline score is reasonable and that the evaluator is fully deterministic (same code + same input = same score).

  • Test with invalid inputs: Run the evaluator with intentionally broken functions to confirm it catches compiler issues, handles infinite loops gracefully, and returns high negative penalty scores.

Avoid over-optimized baselines

Don't pass an already highly optimized baseline program as a seed. If your initial program is already near-optimal, AlphaEvolve will have difficulty hill-climbing because there is very little room to improve. Start with a reasonable but not maximally optimized baseline. This gives AlphaEvolve space to explore and hill-climb.

Client-side runner safeguards

Client-side evaluators must enforce strict safeguards to prevent malicious, resource-intensive, or irresponsive candidates from stalling parallel workers:

  • Strict timeouts: Enforce a strict execution cutoff of 30 minutes (or less depending on the search space structure).

  • Timeout penalty submission: If a candidate program variant exceeds the timeout limit, terminate its execution thread immediately. Don't allow the candidate process to fail. Instead, instantly compile and submit a severe failure penalty score (for example, -100000.0) along with a descriptive debug insight back to the server to release the program's queue lock.

  • AST security filters: Always run an Abstract Syntax Tree (AST) inspection check on the incoming source code payload before compilation. Immediately abort execution and apply a severe failure penalty if restricted reflection or execution primitives (such as eval, exec, getattr, or setattr) are detected.

Further resources

For more information, see the following resources: