
Agent Lightning v1.0: RL Data From Any Agent, No GPU
Summary
Capture real RL training trajectories from any agent using Agent Lightning's CPU-only Gateway.
Microsoft shipped Agent Lightning v1.0 on August 17, 2026 — a full rewrite of its agent-RL framework, down to roughly 3,500 lines of core Python, MIT licensed, and already past 17k GitHub stars. The pitch that made it spread: train any agent with reinforcement learning, with almost zero code changes.
Nearly every writeup about it stops at the same place: "you need an A100 and the verl stack." That is true for the policy-update half. It is not true for the half that actually matters when you are starting out. The piece that turns your agent into something trainable — the API Gateway — is a plain FastAPI service that runs on a laptop CPU with no GPU, no vLLM, and no model weights.
This guide gets you all the way through that half. You will stand up the Gateway, point an ordinary OpenAI-SDK agent at it without touching the agent's logic, and pull back a real training trajectory: prompt token IDs, response token IDs, log probs, and a reward. Along the way you will hit four silent-failure traps that produce empty training data with a 200 OK and no warning. Every command and every output below came from an actual run.
Why the Gateway is the interesting part
Agent Lightning v1.0 splits into three components. Understanding the split is what lets you skip the GPU.
| Component | What it does | Needs a GPU? |
|---|---|---|
| API Gateway | Stores rollouts and events; proxies model calls and records them | No |
| Rollout Controller | Launches agent runs as local processes or Kubernetes Jobs | No |
| Customized Trainer | Runs verl/vLLM, converts events into policy updates | Yes |
The Gateway is the contract between your agent and any training backend. It calls itself an "OpenAI-compatible proxy," and that phrase is doing a lot of work: your agent points its base_url at a rollout-scoped URL, keeps using the OpenAI SDK exactly as before, and the Gateway silently records every call as structured training data.
That means you can adopt Agent Lightning in two stages. Stage one, today, on CPU: instrument the agent and start collecting trajectories. Stage two, whenever you actually have GPUs: attach the trainer to the data you have been collecting all along. Most teams should not skip to stage two.
Prerequisites
- Python 3.11 or newer. The package installs on 3.10, but a transitive litellm dependency imports
NotRequiredfromtyping, which is 3.11+. On 3.10 the import blows up before your code runs. - About 2 GB of disk for the dependency tree (FastAPI, httpx, litellm, OpenTelemetry).
- No GPU, no API key, no model weights. The worked example ships its own upstream.
- Familiarity with the OpenAI Chat Completions API and basic REST.
# uv is the fastest path and pins the interpreter for you
uv venv --python 3.12 agl-env
source agl-env/bin/activate
uv pip install agentlightning openai fastapi uvicorn
python -c "import agentlightning; print(agentlightning.__version__)"
# 1.0.1
Note that import agentlightning exposes no top-level symbols in v1.0. The real surface lives in agentlightning.client, agentlightning.schemas, and two console scripts, agl-server and agl-controller. If you are following an older v0.x tutorial that calls agl.emit_reward(), that API is gone — it lives on the v0.x branch.
Step 1: Start the Gateway
agl-server is configured through Hydra, so every setting is a key=value argument rather than a flag. Run it with --help to see the whole config tree:
agl-server --help
# == Config ==
# host: 0.0.0.0
# port: 8080
# key: ''
# default_proxy:
# model_name: Qwen/Qwen2.5-7B-Instruct
# include_log_probs: true
# train:
# temperature: 1
# val:
# temperature: 0.7
Two things in that output matter more than they look. The default port is 8080, not the 8181 you see in the official Calc-X example — that example overrides it. And default_proxy.model_name defaults to a Qwen checkpoint, which will bite you in Step 3.
Start it, overriding the model name to match the upstream we are about to register:
agl-server port=8181 default_proxy.model_name=demo-model
# [warning] AGL_KEY not set — authentication disabled. Do not use in production.
# [info ] Proxy config loaded model_name=demo-model
# INFO: Uvicorn running on http://0.0.0.0:8181
Confirm it is alive and inspect the routes. The Gateway publishes a full OpenAPI schema, which is the most reliable documentation available for v1.0:
curl -s http://127.0.0.1:8181/healthz
curl -s http://127.0.0.1:8181/openapi.json | python -m json.tool | head -40
The surface is small enough to list in full:
GET /healthz
POST /api/rollouts # batch create
GET /api/rollouts
GET /api/rollouts/terminal # finished runs, for the trainer to drain
GET /api/rollouts/{rollout_id}
PATCH /api/rollouts/{rollout_id} # status transitions only
DELETE /api/rollouts/{rollout_id}
POST /api/rollouts/{rollout_id}/attempt/{attempt_id}/events
GET /api/rollouts/{rollout_id}/events
POST /api/models # register upstream inference endpoints
DELETE /api/models
POST /proxy/rollout/{rollout_id}/attempt/{attempt_id}/mode/{mode}/openai/v1/{path}
POST /proxy/pause
POST /proxy/resume
GET /proxy/state
There is a Python client, AgentLightningSyncClient, but it is a thin subclass of httpx.Client that adds auth headers and retries. It has no domain methods like create_rollout(). Everything is REST, so plain httpx is equally valid and easier to read.
Step 2: Give the Gateway something to proxy to
The Gateway is a reverse proxy. It refuses to serve model calls until a real inference endpoint is registered. In production that endpoint is vLLM serving your policy weights. For this guide we write a tiny stand-in so the example runs anywhere.
This detail is worth pausing on, because it drives the biggest gotcha in the whole framework: the Gateway does not send a vanilla OpenAI request upstream. It injects return_token_ids: true and logprobs: true, because RL needs token IDs and log probs, not text. return_token_ids is a vLLM extension, not part of the OpenAI API. Our mock honors it:
# vllm_like.py — an OpenAI-compatible upstream that mimics vLLM
import time, uvicorn
from fastapi import FastAPI, Request
app = FastAPI()
@app.post("/v1/chat/completions")
async def chat(req: Request):
body = await req.json()
user = [m for m in body["messages"] if m["role"] == "user"][-1]["content"]
answer = "4" if "2+2" in user.replace(" ", "") else "I need a calculator."
resp = {
"id": "chatcmpl-demo", "object": "chat.completion",
"created": int(time.time()), "model": body.get("model", "demo-model"),
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": answer},
"finish_reason": "stop",
"logprobs": {"content": [
{"token": answer, "logprob": -0.12, "top_logprobs": []}
]},
}],
"usage": {"prompt_tokens": 12, "completion_tokens": 3, "total_tokens": 15},
}
# The Gateway asks for this. Vanilla OpenAI would 400 on the unknown field.
if body.get("return_token_ids"):
resp["prompt_token_ids"] = [3923, 374, 220, 17, 10, 17, 30]
resp["choices"][0]["token_ids"] = [19, 128009]
return resp
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=9002, log_level="error")
Run it in a second terminal with python vllm_like.py, then register it. Note the endpoint is a list — registration is an upsert keyed by (model, endpoint), so re-registering the same pair bumps the version rather than duplicating it.
import httpx
AGL = "http://127.0.0.1:8181"
models = httpx.post(f"{AGL}/api/models", json=[
{"model": "demo-model", "endpoint": "http://127.0.0.1:9002/v1", "version": 1}
]).json()
print(models)
# [{'model': 'demo-model', 'endpoint': 'http://127.0.0.1:9002/v1', 'version': 1}]
The version field is how the trainer signals a weight update. Each time the policy changes, it re-registers the endpoint with an incremented version, and every recorded call carries the version it was generated under — so off-policy samples are identifiable after the fact.
Step 3: Create a rollout and claim an attempt
A rollout is one execution of your agent on one input. It is not the same as a training example: GRPO and similar algorithms create several rollouts from one example so rewards can be compared against each other.
First trap: POST /api/rollouts takes a list and returns a list. Posting a bare object gives you a 422 that reads Input should be a valid list.
rollouts = httpx.post(f"{AGL}/api/rollouts", json=[{
"input": {"question": "What is 2+2?", "answer": "4"},
"is_train": True,
"metadata": {"batch_idx": 0, "sample_idx_in_batch": 0},
}]).json()
rollout = rollouts[0]
rid = rollout["rollout_id"]
print(rid, rollout["status"]["state"])
# 35ef62af40904fceade13c3e71184ca6 queuing
The input field is untyped — put whatever your agent needs in it, including the ground-truth answer, since only your reward function reads it. is_train chooses the temperature profile (1.0 for train, 0.7 for val by default) and keeps validation rollouts out of the gradient.
Second trap, and this one is genuinely nasty. A fresh rollout is in state queuing with last_attempt_id: null. Normally the Rollout Controller claims it and assigns an attempt. We are running the agent by hand, so we have to claim it. Skip this and your model calls still return 200 — but the Gateway drops the recording, and GET /events comes back empty with no error anywhere.
httpx.patch(f"{AGL}/api/rollouts/{rid}", json={
"status": {"state": "running", "last_attempt_id": "a1"}
})
You choose the attempt ID. It exists so a retried rollout keeps its failed transcripts separate from the successful one. Only the nested status object is patchable — the Gateway rejects attempts to modify input or metadata after creation.
Step 4: Point your agent at the proxy
Here is the zero-code-change claim, made concrete. Your agent keeps its framework, its tools, its control flow, its prompts. The only thing that changes is base_url:
from openai import OpenAI
base = f"{AGL}/proxy/rollout/{rid}/attempt/a1/mode/train/openai/v1"
client = OpenAI(base_url=base, api_key="unused") # api_key is ignored
resp = client.chat.completions.create(
model="demo-model",
messages=[{"role": "user", "content": "What is 2+2?"}],
)
out = resp.choices[0].message.content
print(out)
# 4
The rollout ID is baked into the URL path, which is the trick that makes instrumentation free. There is no context variable to thread, no callback to register, no decorator to apply. Every call made against that base URL is attributed to that rollout automatically — including calls made from deep inside LangChain, CrewAI, AutoGen, or the OpenAI Agents SDK, none of which need to know Agent Lightning exists.
Swap mode/train for mode/val to use the validation temperature.
Third trap: the Gateway overrides the model field you send. It substitutes default_proxy.model_name before forwarding. If you leave the default and register an endpoint under a different name, every call fails with:
openai.InternalServerError: Error code: 503 -
{'detail': "No servers available for model 'Qwen/Qwen2.5-7B-Instruct'"}
The fix is what we already did in Step 1 — set default_proxy.model_name to match the registered model. The error message is clear once you see it, but nothing in the SDK hints that your model= argument was discarded.
Step 5: Report the reward
The Gateway records model calls on its own. Rewards it cannot know about — those come from your evaluator. Append one as an event on the same rollout and attempt:
reward = 1.0 if out.strip() == "4" else 0.0
httpx.post(f"{AGL}/api/rollouts/{rid}/attempt/a1/events", json={
"event_type": "reward",
"data": {"value": reward, "source": "exact_match"},
})
httpx.patch(f"{AGL}/api/rollouts/{rid}", json={"status": {"state": "succeeded"}})
Fourth trap, and the most expensive one in this guide: the reward key is value, not reward.
The Gateway's own source calls RewardData a "documentation/validation helper" and notes it is not enforced by the Store. Event payloads are opaque pass-through. So posting {"reward": 1.0} returns a cheerful 200, stores your dict verbatim, and shows up correctly in the raw event feed. It only falls apart at the last step, when the trainer asks for training format and gets:
{"event_type": "reward", "data": {"value": null}}
Every reward silently becomes null. Advantages compute to zero. The loss goes nowhere, the run looks healthy, and you burn GPU hours training on no signal. There is no warning at any layer. Set value.
The optional source, reason, and message fields are free-form and survive into the trajectory, which makes them useful for tagging which grader produced a score when you run several.
Step 6: Read back the trajectory
The raw feed shows everything the Gateway captured — request, response, latency, HTTP status, retry count, token usage:
events = httpx.get(f"{AGL}/api/rollouts/{rid}/events").json()
print([e["event_type"] for e in events])
# ['model_request', 'reward']
That is useful for debugging, but it is not what a trainer wants. Add format=triplet to strip everything except what RL consumes:
triplet = httpx.get(
f"{AGL}/api/rollouts/{rid}/events",
params={"format": "triplet"},
).json()
print(json.dumps(triplet, indent=2))
Real output from the run:
[
{
"event_type": "model_request",
"rollout_id": "35ef62af40904fceade13c3e71184ca6",
"attempt_id": "a1",
"timestamp": 1787756964.860611,
"data": {
"prompt_token_ids": [3923, 374, 220, 17, 10, 17, 30],
"response_token_ids": [19, 128009],
"response_log_probs": [-0.12],
"server": {"model": "demo-model", "version": 1},
"http_status": 200,
"status": "ok"
}
},
{
"event_type": "reward",
"rollout_id": "35ef62af40904fceade13c3e71184ca6",
"attempt_id": "a1",
"timestamp": 1787756964.8823733,
"data": {"value": 1.0, "source": "exact_match"}
}
]
That is a complete RL training sample, produced on a CPU by an agent that was never modified. Tokens in, tokens out, log probs, and a scalar reward — everything GRPO or PPO needs.
Notice there are no strings left. The trainer never sees your prompt text; it sees token IDs. This is deliberate, and it is the point of the vLLM team's writeup on retokenization drift: if you log text and re-tokenize it at training time, the token boundaries can differ from what the model actually sampled, and your gradients are computed against a sequence the policy never produced. Returning token IDs through the API is what avoids that.
Finally, the trainer drains finished work through a dedicated endpoint:
print(httpx.get(f"{AGL}/api/rollouts/terminal").text)
# {"items":[{"rollout_id":"35ef62af...","state":"succeeded","data_id":"","is_train":true}],
# "next_after":1,"total_terminal":1}
next_after is a cursor, so a training loop can poll this endpoint and pick up only rollouts it has not already consumed.
Worked example: a scored batch, end to end
Putting it together into the shape you would actually run — a batch of examples, each scored, each producing a trajectory. This is the loop a trainer sits on top of.
# harness.py — CPU-only. Requires agl-server and vllm_like.py running.
import json, httpx
from openai import OpenAI
AGL = "http://127.0.0.1:8181"
DATASET = [
{"question": "What is 2+2?", "answer": "4"},
{"question": "What is 17*23?", "answer": "391"},
{"question": "What is 2 + 2 ?", "answer": "4"},
]
# 1. Register the inference endpoint once.
httpx.post(f"{AGL}/api/models", json=[
{"model": "demo-model", "endpoint": "http://127.0.0.1:9002/v1", "version": 1}
])
# 2. Create the whole batch in one call.
rollouts = httpx.post(f"{AGL}/api/rollouts", json=[
{"input": ex, "is_train": True,
"metadata": {"batch_idx": 0, "sample_idx_in_batch": i}}
for i, ex in enumerate(DATASET)
]).json()
def run(rollout):
rid = rollout["rollout_id"]
ex = rollout["input"]
attempt = "a1"
# 3. Claim the attempt, or recording is silently skipped.
httpx.patch(f"{AGL}/api/rollouts/{rid}",
json={"status": {"state": "running", "last_attempt_id": attempt}})
base = f"{AGL}/proxy/rollout/{rid}/attempt/{attempt}/mode/train/openai/v1"
client = OpenAI(base_url=base, api_key="unused")
try:
# 4. Your unmodified agent. Swap in any framework here.
out = client.chat.completions.create(
model="demo-model",
messages=[{"role": "user", "content": ex["question"]}],
).choices[0].message.content
reward = 1.0 if out.strip() == ex["answer"] else 0.0
state = "succeeded"
except Exception as e:
out, reward, state = str(e), 0.0, "failed"
# 5. Reward key is "value". Not "reward".
httpx.post(f"{AGL}/api/rollouts/{rid}/attempt/{attempt}/events",
json={"event_type": "reward",
"data": {"value": reward, "source": "exact_match"}})
httpx.patch(f"{AGL}/api/rollouts/{rid}", json={"status": {"state": state}})
return rid, ex["question"], out, reward
for rid, q, out, r in [run(x) for x in rollouts]:
print(f"{r:>4} {q:<18} -> {out}")
# 6. Pull the batch as training data.
terminal = httpx.get(f"{AGL}/api/rollouts/terminal").json()
print(f"\n{terminal['total_terminal']} terminal rollouts")
for item in terminal["items"]:
t = httpx.get(f"{AGL}/api/rollouts/{item['rollout_id']}/events",
params={"format": "triplet"}).json()
calls = [e for e in t if e["event_type"] == "model_request"]
rew = next((e["data"]["value"] for e in t if e["event_type"] == "reward"), None)
tok = sum(len(c["data"]["response_token_ids"]) for c in calls)
print(f" {item['rollout_id'][:8]} calls={len(calls)} tokens={tok} reward={rew}")
Output:
1.0 What is 2+2? -> 4
0.0 What is 17*23? -> I need a calculator.
1.0 What is 2 + 2 ? -> 4
3 terminal rollouts
39dd3ce0 calls=1 tokens=2 reward=1.0
9a2a8ea5 calls=1 tokens=2 reward=0.0
d4858c88 calls=1 tokens=2 reward=1.0
Two of three correct, and the failure is the interesting one — the toy model punts on multiplication instead of guessing. That is exactly the signal RL would push on: a real run would give the agent a calculator tool, and the reward would teach it when to reach for it. The official Calc-X example does precisely this with AutoGen and an MCP calculator server.
The tokens=2 figure is the give-away that this is a mock upstream. Against real vLLM you would see full sequences here, and that number is worth asserting on in tests — see the pitfalls below.
Pitfalls worth internalizing
Every one of these returns a 200 and looks fine.
- Reward key is
value. Posting{"reward": 1.0}stores fine and reads back fine in the raw feed, then becomes{"value": null}in triplet format. Silent, total loss of training signal. - Claim the attempt before calling the proxy. A rollout in
queuingwith a nulllast_attempt_idwill happily serve model calls and record none of them. PATCH torunningwith an explicit attempt ID first. - The
modelfield is overridden. The Gateway substitutesdefault_proxy.model_name. Your SDK'smodel=argument is decorative. Mismatch produces a 503 that names a model you never referenced. /api/rolloutsis batch-only. Takes a list, returns a list. A bare object is a 422.- Your upstream must return token IDs. The Gateway injects
return_token_ids: true, a vLLM extension. Plain OpenAI-compatible servers ignore it, and triplet format then returnsprompt_token_ids: []andresponse_log_probs: null— structurally valid, completely untrainable. - Python 3.10 fails at import. A litellm dependency needs
typing.NotRequired. Use 3.11+. - Default port is 8080. The docs' example uses 8181 via an override. Do not assume.
- Auth is off by default. The startup log warns
AGL_KEY not set. The Gateway proxies to your inference endpoint and stores full prompts and completions — setAGL_KEYbefore it touches a shared network. - v0.x tutorials do not apply. Anything calling
agl.emit_reward()orLitAgentpredates the rewrite. v1.0 has no top-level exports.
A cheap guard that catches the two worst ones at once — put it at the end of your first real run, before you rent a GPU:
def assert_trainable(agl, rollout_id):
t = httpx.get(f"{agl}/api/rollouts/{rollout_id}/events",
params={"format": "triplet"}).json()
calls = [e for e in t if e["event_type"] == "model_request"]
rewards = [e for e in t if e["event_type"] == "reward"]
assert calls, "no model_request events — did you claim the attempt?"
assert rewards, "no reward event on this rollout"
assert rewards[0]["data"].get("value") is not None, \
"reward is null — the payload key must be 'value', not 'reward'"
assert calls[0]["data"]["prompt_token_ids"], \
"empty prompt_token_ids — upstream ignored return_token_ids"
return sum(len(c["data"]["response_token_ids"]) for c in calls)
Quick reference
| Task | Call |
|---|---|
| Start Gateway | agl-server port=8181 default_proxy.model_name=NAME |
| Inspect API | GET /openapi.json |
| Register upstream | POST /api/models — list of {model, endpoint, version} |
| Create rollouts | POST /api/rollouts — list of {input, is_train, metadata} |
| Claim attempt | PATCH /api/rollouts/{id} — {status:{state:running, last_attempt_id}} |
| Agent base_url | /proxy/rollout/{id}/attempt/{aid}/mode/train/openai/v1 |
| Report reward | POST .../events — {event_type:reward, data:{value: float}} |
| Raw trajectory | GET /api/rollouts/{id}/events |
| Training data | GET /api/rollouts/{id}/events?format=triplet |
| Drain finished | GET /api/rollouts/terminal — cursor in next_after |
| Pause proxy | POST /proxy/pause / POST /proxy/resume |
| Rollout states | queuing, running, succeeded, failed |
Where to go next
You now have the half of Agent Lightning that runs anywhere. Three directions from here, roughly in order of effort:
- Instrument the agent you already have. Change one
base_url, add a reward call, and start banking trajectories. Even with no training attached, you get a queryable log of every model call with latency, token usage, and a score — which is a decent eval harness on its own. - Hand execution to the Controller.
agl-controller runner_type=localtakes over claiming rollouts and running your agent as a subprocess, so you stop writing the PATCH-to-running dance by hand. Kubernetes mode runs each rollout as a Job, which is how v1.0 drops the external sandbox service that v0.x needed. - Attach the trainer. This is where the A100 arrives. Follow the official installation guide for the verl stack, then work through the Calc-X example, which trains a math agent with AutoGen and MCP calculator tools and covers reward-hacking prevention.
If you want the design rationale, the v1.0 paper is arXiv:2608.17528, "Agent Lightning v1.0: Towards Harnessed Agentic RL." The term "harnessed" is the thesis: the deploy-time harness owns the loop with the environment, and the training engine adapts to it — rather than the usual arrangement where you rewrite your agent to fit the trainer.
That inversion is why the Gateway can be useful before you own a single GPU.
Sources
- microsoft/agent-lightning — source, MIT licensed
- Agent Lightning v1.0 documentation — architecture, Basics, Quick Start
- arXiv:2608.17528 — Agent Lightning v1.0: Towards Harnessed Agentic RL
- vLLM blog — why token IDs must come back through the API
- Microsoft Research — LightningRL and credit assignment
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,617 newsletter subscribers.