Tutorial

From nothing to a trajectory

A complete path from first principles to a real run: install, choose an entry point, understand the session tree, extend a capability, inspect and export training data, operate the Web UI safely, and know exactly what the system does—and does not—do today.

13 chaptersCLI + Web UISFT/RL trajectory exportTroubleshooting included

00Build the right mental model first

AgentEvolver is not just a chat interface and not a trainer. It is an agent runtime that connects four loops: execute work, observe every important event, evaluate the result, and preserve reusable improvements. The current release evolves capabilities and produces training-ready records; integrated weight training and model feedback are the destination, not a hidden feature.

Available now

Multi-agent execution; tools, skills, environments, connectors and workflows; evaluation; staged/versioned extension promotion and rollback; trace plus reward-annotated trajectory capture; SFT and pluggable RL export.

Roadmap

A trainer provider, tokenizer annotation, dataset curation, checkpoint registry, automated train/evaluate gates, and feeding an approved model version back into serving.

The end-to-end direction

Run real tasks

The MetaAgent delegates to specialists, capabilities act in a shared project, and review may send weak work back.

Collect faithful trajectories

Keep the exact effective prompt, reasoning, native calls, observations, usage, failures, and late reward.

Train and evaluate

Export today; later, invoke an in-system SFT/RL provider, register checkpoints, and compare them on versioned benchmarks.

Serve only an approved winner

The future feedback gate should update a model role only after evaluation and human/policy approval, with rollback retained.

01Install

Python 3.11 or newer. The editable install is the one to use while reading the code, because every module is discovered by import and an editable tree keeps that honest.

git clone https://github.com/DVampire/AgentEvolver.git
cd AgentEvolver
pip install -e ".[dev]"

Verify. The suite should be green before you change anything, so that the first red you see is yours:

pytest -q

02Configure a model

Models are selected by role rather than by name at each call site, so swapping the model behind "the main one" is a config change and not a search-and-replace.

# .env
OPENAI_API_KEY=sk-...
# or any provider the model registry knows — see agentevolver/model/
Why

Retries are deliberately not configured here. Every provider adapter passes max_retries=0 to its SDK, because two retry layers multiply — three application attempts over five SDK attempts is fifteen requests nobody chose — and the SDK's attempts reach neither the log nor the trajectory.

03Choose the entry point that matches your goal

All interactive surfaces converge on one Gateway backend, but they serve different workflows. Start with the smallest surface that can prove your setup.

EntryUse it forCommand
Control commandInspecting the registry, checkpoints, and framework stateagentevolver /registry
TUIAn interactive terminal session without Node.jsagentevolver tui --config configs/meta_agent.py
Example runnerReproducible experiments and task documentspython examples/run_meta_agent.py --task "..."
Web UIChat, Canvas, IDE and Science in one projectbash scripts/serve-ui.sh
First verification

Run agentevolver /registry. If the Gateway can initialize the configured managers and print their registered names, installation, imports and base configuration are already connected.

04Run a task

Two development processes, one backend path: Gateway owns runtime state and the Vite server serves the UI. The browser opens the UI port and connects to Gateway's WebSocket port; the convenience script starts and shuts down both together.

# terminal 1
agentevolver serve --transport websocket --port 9876

# terminal 2
cd frontend && npm install && npm run dev

Open the UI, type a task, and watch the middle column. What you are seeing is not a transcript being streamed at you — it is the log being rendered as it is written.

What happens when you send a task You a task, in words MetaAgent plans · delegates Specialist agent tools · skills · env Specialist agent runs in parallel Review accept or send back not good enough — go round again Trajectory kept either way
A run that is sent back and retried produces a trajectory too. Failed attempts are the part of the record that a training set most needs and most often lacks.

05Read the session output tree

A run should be inspectable without the UI that created it. Paths are resolved centrally and rebound to the session, so generated state stays under output/ while promoted, shareable extensions stay under extension/.

output/<owner>/sessions/<session-id>/ ├── workspace/ files the agent and IDE edit ├── log/ │ ├── trajectory/ one <task-id>.jsonl per recorded run │ └── tasks/ durable task status and results ├── conversations/ transcript events and metadata ├── flows/ · runs/ Canvas drafts and run indexes └── session.json identity, roots and staged inputs extension/ ├── agent/ · tool/ · skill/ · environment/ … └── canvas/ reusable visual flow graphs
  • Use identifiers, not timestamps, to correlate. Session id groups a project interaction; task id names one run and is the key used for trajectory reward/export.
  • Do not edit generated state as configuration. Change configs/*.py or versioned extensions; output/ is evidence and runtime state.
  • Do not put promoted extensions in the package tree. Separation keeps generated changes reviewable and reversible.

06Add a tool

One file, one export, one test. The agent can use it on the next run — there is no registry file to edit.

# agentevolver/tool/default/word_count.py
class WordCountTool(Tool):
    """Count the words in a file."""

    name: str = Field(default="word_count")          # a CLASS field
    description: str = Field(default="Count words in a UTF-8 text file.")
    mutates: bool = Field(default=False)             # reports only; never writes

    async def __call__(self, path: str, ctx=None, **kwargs) -> Response:
        with open(path, encoding="utf-8") as handle:
            count = len(handle.read().split())
        return Response(type=ResponseType.TOOL, success=True,
                        message=f"{count} words", data={"words": count})
# agentevolver/tool/default/__init__.py
from .word_count import WordCountTool

Verify. Registration is what to check, not the import:

python -c "
import asyncio
from agentevolver.tool import tool_manager
asyncio.run(tool_manager.initialize())
print('word_count' in asyncio.run(tool_manager.list()))"
Trap

Three things silently produce a tool the model can never call: a name passed to the constructor instead of declared as a class field, a class that is written but never exported, and a __call__ that returns something other than a Response — the last leaves the agent holding None, so the run spins with no observation and no error.

07Read and export the trajectory

This is the step that explains the project. A run leaves a step-level record — what the model saw, what it decided, what came back, what it cost, and what the attempt was ultimately worth.

output/<owner>/sessions/<session>/log/trajectory/<task>.jsonl

line 1   the header: session, task, agent, outcome, reward
line 2+  one step each: messages sent · reasoning · actions · usage

Two properties are worth checking yourself, because they are what make the record usable as training data rather than as telemetry:

  • Failures are in there. A model call that failed twice and succeeded on the third try records all three. A record that showed only the success would describe a model that got it right first time — a sample that lies about what happened.
  • The reward reaches every step. A benchmark scores a run after it ends, and the score is backfilled to the steps that produced it. A trajectory with no reward is a run the corpus counts as worth nothing.

What one step means

{
  "step_number": 2,
  "messages_sent": [...],   // z_t: effective prompt, after hooks/compaction
  "reasoning": "...",       // model text/thinking used as assistant target
  "actions": [...],         // a_t: native tool calls, names + JSON arguments
  "observations": [...],    // o_t: result/error for every attempted action
  "usage": {...},           // input/output/cache tokens and cost when available
  "reward": 0.8             // r_t: task score, backfilled after evaluation
}

Load a finished run and export both formats

import json
from agentevolver.trajectory import trajectory_manager, VerlFormat

trajectory = trajectory_manager.load("output/.../log/trajectory/<task-id>.jsonl")
assert trajectory is not None

# One OpenAI-chat record per step; assistant tool_calls stay native.
sft_records = trajectory.to_sft_records()

# Text-level VERL episodes. A trainer provider adds tokenizer-specific ids/masks.
rl_records = trajectory.to_rl_records(VerlFormat())

print(json.dumps(sft_records[0], ensure_ascii=False, indent=2))
Data governance

A faithful trajectory may contain user text, file content, tool arguments, external responses and model reasoning. Before turning logs into a corpus, add task-specific redaction, consent/retention rules, deduplication, quality filters and train/eval leakage checks. “Exportable” does not automatically mean “safe to train on.”

08Operate the Web UI

The four surfaces are views of one project, not four copies. Chat observes the event log, Canvas authors workflows, IDE edits the workspace, and Science shares a live Jupyter kernel.

SurfaceState it ownsTypical use
ChatConversation and streamed Gateway eventsSubmit tasks, answer questions, inspect actions/results
CanvasJSON FlowGraphCompose and run visual workflows on WorkflowRuntime
IDEThe same session workspaceReview or edit files beside the agent
ScienceThe shared project kernelExplore data, keep variables, open notebooks

Open the complete Web UI guide, including startup, state model, Canvas, IDE and Science →

09Choose sandbox and permission boundaries deliberately

Permission answers whether an operation is allowed; Sandbox contains where it can act; Plan mode prevents mutation before approval. These layers complement one another and should not be treated as aliases.

Permission

Classifies command/filesystem intent with explicit modes and composable rules. Use it for policy and approval decisions.

Sandbox

Selects a backend, binds project paths, controls egress and records resources for cleanup. Use it for containment.

Plan

Allows reading and reasoning while refusing mutating capabilities until a person approves the plan.

Constraint

Enforces step/token/time budgets and tells the model when remaining capacity is tight or critical.

Remote serving

Binding Gateway to a non-loopback host requires --token or AGENTEVOLVER_GATEWAY_TOKEN. Set explicit allowed origins as well; do not expose a development Gateway as an unauthenticated public service.

10Understand a component evolution round

Evolution is evidence-driven component engineering, not arbitrary self-modification. A recurring or measured gap justifies a candidate; the candidate stays outside the core and must cross explicit gates.

Establish the gap

Use a failing task, benchmark delta or repeated structural defect. A first ordinary bug should normally be fixed directly.

Generate into staging

Dynamic loading derives metadata, while Version records lineage and Extension owns the manifest.

Register under a Scope

Every registration gains a reverse operation, so a partial failure can still uninstall what succeeded.

Evaluate and replay

Tests, task evaluation and replay smoke checks produce evidence before promotion.

Promote or roll back

Promotion is journaled; rejection or later regression restores the prior registered version.

11Troubleshoot from the boundary inward

SymptomCheck firstWhy
A capability never appearsagentevolver /registry, config whitelist, module exportImported code and registered capability are not the same fact.
The run loops with no useful observationCapability return type and Trace POST_ACTION eventA missing normalized Response breaks the agent/capability boundary.
Trajectory file is absentSession log root; trajectory_manager and hook_manager initializationCapture is fed by hooks and persistence is session-bound.
Reward remains zeroUse task_id with set_reward, or set_reward_by_sessionEvaluation arrives after finalize and must correlate to the recorded run.
Web UI connects but shows no runGateway URL/token/origin and session.create responseThe UI is a client; it cannot invent backend session state.
Sandbox cannot reach a servicenetwork flag, allow/deny hosts, model endpoint allowanceDeny wins; network=false with an allowlist uses the relay only for listed hosts.

Recommended order: reproduce with the smallest entry point → inspect Gateway/manager initialization → inspect Trace → inspect the owning module’s README and schema → then inspect provider or sandbox logs.

12Where to go next