> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.world/llms.txt
> Use this file to discover all available pages before exploring further.

# PlannerGeneratorEvaluator Guide

> Turn a short prompt into a graded plan, then build it step by step while a separate evaluator scores each step and sends weak work back

`PlannerGeneratorEvaluator` (PGE) runs three agents. A planner expands your short prompt into a plan of numbered steps and a set of scoring criteria. For each step, a generator does the work and a separate evaluator scores it against the criteria. A step that scores below a threshold goes back to the generator with the evaluator's feedback, up to a retry limit. Keeping the maker and the grader apart stops the generator from grading its own work.

All three agents share one Markdown file on disk. Every call gets the whole file, and every reply is appended to it, so the file is a complete record of the run.

Reference: [PlannerGeneratorEvaluator](https://docs.swarms.world/api/planner-generator-evaluator.md).

## How one step runs

| Stage | Agent | Writes to the shared file |
| - | - | - |
| Contract | Generator | What "done" means for this step: acceptance criteria and how to check them |
| Contract review | Evaluator | Approved, or amendments. The step runs either way, and amendments stay in the file for the generator to read |
| Work | Generator | The step's output |
| Evaluation | Evaluator | A score for each criterion. A score under its threshold fails the step |
| Retry | Generator | A new attempt that gets the evaluator's full reply. From the second retry it is also told whether scores are improving (refine) or not (pivot) |

## 1. Run the harness

`model_name` sets the model for all three agents. `max_steps` caps how many plan steps run, and `max_retries_per_step` caps the retries after a failed evaluation.

```python theme={null}
from swarms import PlannerGeneratorEvaluator

harness = PlannerGeneratorEvaluator(
    model_name="gpt-5.4-mini",
    max_steps=2,
    max_retries_per_step=1,
    working_directory="pge_runs",
)

history = harness.run(
    "Write a one-page guide to keeping a sourdough starter alive: "
    "feeding schedule and common mistakes."
)

for message in history:
    print(f"--- {message['role']}")
    print(message["content"][:200])
```

The default `output_type="dict"` returns the whole conversation as a list of messages:

| Role | Content |
| - | - |
| `User` | Your prompt |
| `PGE-Planner` | The plan, with steps and an evaluation criteria table |
| `PGE-Generator` | Labelled `[Step 1 Contract]`, `[Step 1 Output (attempt 1)]` and so on |
| `PGE-Evaluator` | Labelled `[Step 1 Contract Review]`, `[Step 1 Evaluation]` and so on |
| `System` | Progress markers such as `--- Step 1/2 PASSED ---`, and a closing summary |

> [!NOTE]
>
> The harness reads the number of steps from the plan (the highest `Step N`) and runs only the first `max_steps` of them. With `max_steps=2`, a plan of five steps stops after step 2, so the output covers only part of the plan. Raise `max_steps` (default 10) for a complete result.

## 2. Read the result

After `run()`, `harness.last_result` holds the run's numbers, the plan and one log per step. `output_path` is the shared file.

```python theme={null}
result = harness.last_result

print(f"Steps passed: {result.total_steps_completed}")
print(f"Retries: {result.total_retries}")
print(f"Duration: {result.total_duration:.1f}s")
print(f"Shared state file: {result.output_path}")

for step in result.step_logs:
    print(
        f"Step {step['step_number']}: passed={step['passed']} "
        f"retries={step['retries']} contract approved={step['contract']['approved']}"
    )
    for evaluation in step["evaluations"]:
        print("  scores:", evaluation["criterion_scores"])

with open(result.output_path) as f:
    print(f.read()[:800])
```

Each evaluation scores the criteria the planner defined, five in our runs, such as `'feeding schedule clarity': 9.0`. A step that needed a retry has one set of scores per attempt. In one run, step 2 first scored 1.0 on `coverage of common mistakes`, then passed on its retry with 7.0. The file starts with a `# PGE Harness Shared State` header and your prompt, followed by one timestamped section per agent call: `[PLANNER OUTPUT]`, `[STEP 1 CONTRACT PROPOSAL]`, `[STEP 1 CONTRACT REVIEW]`, `[STEP 1 WORK LOG]`, `[STEP 1 EVALUATION]`, and a final `[HARNESS SUMMARY]`.

The finished work is in the generator's work logs: the `[Step N Output ...]` messages, or the `WORK LOG` sections of the file. Each `run()` rewrites the file and clears the conversation, so one harness can run many prompts. The file name includes the harness `id`; pass `shared_state_path` to choose it.

## 3. Use a stronger grader and allow more retries

Each role can have its own model: `planner_model_name`, `generator_model_name` and `evaluator_model_name` override `model_name`. A stronger evaluator gives stricter, more useful feedback. Here `output_type="final"` returns only the last message, the closing summary.

```python theme={null}
strict = PlannerGeneratorEvaluator(
    model_name="gpt-5.4-mini",
    evaluator_model_name="gpt-5.4",
    max_steps=2,
    max_retries_per_step=2,
    working_directory="pge_runs",
    output_type="final",
)

summary = strict.run(
    "Write a short explainer on how compound interest works, with one "
    "worked example."
)
print(summary)

for step in strict.last_result.step_logs:
    for attempt, evaluation in enumerate(step["evaluations"], start=1):
        print(f"Step {step['step_number']} attempt {attempt}: passed={evaluation['passed']}")
        for criterion, score in evaluation["criterion_scores"].items():
            threshold = evaluation["criterion_thresholds"].get(criterion)
            print(f"  {criterion}: {score} (needs {threshold})")
```

The summary reads like `PGE Harness completed: 0/2 steps passed, 6 total retries, 98.6s elapsed. Shared state: ...`. In that run, the `gpt-5.4` evaluator held both steps to its thresholds. Step 1 failed on `worked example correctness` (2.0, needs 8.0), fixed it on the retry, then fell short on `brevity and focus` (6.0 and 4.0, needs 7.0). After its retries ran out, the harness moved on. A step that fails every attempt is logged with `passed=False`, and the run still completes.

### How a step passes

The evaluator's reply is read in this order:

1. **Score table rows** like `| clarity | 7 | 8 | FAIL |`. Each score is compared with the threshold in its own row. The built-in evaluator prompt asks for this table, so this is the usual case.
2. **Inline scores** like `Clarity: 7/10`. Each is compared with the threshold the planner set for that criterion, then with `default_thresholds`, then with 6.0.
3. **No scores.** An `Overall Status: PASS` or `FAIL` line decides; with neither, the step passes.

So `default_thresholds={"accuracy": 8.0}` only takes effect when the evaluator writes inline scores and the criterion is named exactly `accuracy` (names are compared in lowercase).

`total_retries` counts every failed evaluation, including the last one on a step that runs out of retries. A step that fails three times with `max_retries_per_step=2` adds 3 and moves on.

## 4. Give the agents tools

Pass your own `planner_agent`, `generator_agent` or `evaluator_agent` to add tools, MCP servers or any other `Agent` setting. A custom agent keeps its own model and system prompt; the matching `*_model_name` and `*_system_prompt` arguments are not applied to it. Here the generator saves its work to files and the evaluator can open them.

```python theme={null}
import os

from swarms import Agent, PlannerGeneratorEvaluator

OUTPUT_DIR = "pge_runs/files"
os.makedirs(OUTPUT_DIR, exist_ok=True)


def write_file(filename: str, content: str) -> str:
    """Write text to a file in the output folder.

    Args:
        filename: The file name, for example notes.md.
        content: The text to write.

    Returns:
        str: A confirmation with the path written.
    """
    path = os.path.join(OUTPUT_DIR, os.path.basename(filename))
    with open(path, "w") as f:
        f.write(content)
    return f"Wrote {path}"


def read_file(filename: str) -> str:
    """Read a file from the output folder.

    Args:
        filename: The file name, for example notes.md.

    Returns:
        str: The file's text, or a message if it does not exist.
    """
    path = os.path.join(OUTPUT_DIR, os.path.basename(filename))
    if not os.path.exists(path):
        return f"{path} does not exist"
    with open(path) as f:
        return f.read()


generator = Agent(
    agent_name="PGE-Generator",
    system_prompt=(
        "You execute one step of a plan at a time. Save every deliverable "
        "with write_file, then report what you wrote."
    ),
    model_name="gpt-5.4-mini",
    max_loops=2,
    tools=[write_file],
    output_type="final",
)

evaluator = Agent(
    agent_name="PGE-Evaluator",
    system_prompt=(
        "You grade a step's output. Open the files the generator says it "
        "wrote with read_file, then score each criterion from 1 to 10 in a "
        "table: | criterion | score | threshold | PASS/FAIL |."
    ),
    model_name="gpt-5.4-mini",
    max_loops=2,
    tools=[read_file],
    output_type="final",
)

harness = PlannerGeneratorEvaluator(
    model_name="gpt-5.4-mini",
    generator_agent=generator,
    evaluator_agent=evaluator,
    max_steps=2,
    max_retries_per_step=1,
    working_directory="pge_runs",
    output_type="final",
)

print(harness.run("Write a README.md for a small command-line todo app."))
print(os.listdir(OUTPUT_DIR))
```

A custom evaluator replaces the built-in evaluator prompt, so tell it to score in the table format above, or the harness cannot read its scores. `max_loops=2` gives each agent room to call its tool and then answer, and `output_type="final"` makes each run return only that answer. In our run both steps passed and the folder held four files. The generator is also asked to write each step's contract, so it saved those too: `step1_contract.md`, `step1_output.md`, `step2_contract.md` and `step2_output.md`.

## Other methods

* `harness(task)` is the same as `harness.run(task)`.
* `batched_run(tasks)` runs the harness on each prompt one after another and returns a list of results.
* `get_harness_result()` returns the harness `id`, `name`, `shared_state_path` and the conversation.
* `harness.usage` sums the token usage of the three agents.

`run()` raises `ValueError` for an empty task. The constructor raises `ValueError` when `max_steps` is below 1, `max_retries_per_step` is below 0, or `model_name` is empty.

## Next steps

* [PlannerGeneratorEvaluator reference](https://docs.swarms.world/api/planner-generator-evaluator.md)
* [PlannerWorkerSwarm guide](https://docs.swarms.world/examples/multi-agent/planner-worker-swarm-example.md) for parallel workers instead of one generator
* [Runnable scripts](https://github.com/kyegomez/swarms/tree/master/examples/multi_agent/planner_generator_evaluator)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.