"""APIShift FastAPI app — the OpenEnv server entry point.
Built on top of openenv-core's create_fastapi_app, which provides the
official OpenEnv contract:
HTTP endpoints (stateless — one env instance per request):
POST /reset POST /step GET /state GET /schema
GET /metadata GET /health GET /docs
WebSocket endpoint (stateful — one env instance per connection):
/ws with messages {"type": "reset"|"step"|"state"|"close", "data": {...}}
Because APIShift's Manager runs multi-step episodes (Diff → Patch → Test
→ Rollback → Submit), the canonical transport is the WebSocket /ws
endpoint, where one connection == one episode. The HTTP /reset and /step
remain available for stateless one-shot calls.
In addition to the openenv-core endpoints we mount three GET routes that
expose the inspectable artifacts (program, lessons, curriculum) so judges
and reviewers can fetch them directly without cloning the repo.
"""
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse
from models import APIShiftAction, APIShiftObservation
from server.environment import APIShiftEnvironment, list_tasks
# ---------------------------------------------------------------------
# Build the OpenEnv-standard FastAPI app
# ---------------------------------------------------------------------
# create_fastapi_app expects a *factory* (callable returning a fresh env
# per call). Our env constructor takes no required arguments, so passing
# the class itself works. Each new HTTP request gets its own instance;
# each WebSocket connection gets its own dedicated session env.
try:
from openenv.core.env_server import create_fastapi_app
app: FastAPI = create_fastapi_app(
APIShiftEnvironment,
APIShiftAction,
APIShiftObservation,
)
_OPENENV_AVAILABLE = True
except ImportError:
# Fallback for local dev without openenv-core installed.
_OPENENV_AVAILABLE = False
app = FastAPI(title="APIShift", version="0.1.0")
_env = APIShiftEnvironment()
@app.post("/reset")
async def reset_endpoint(req):
body = await req.json()
obs = _env.reset(**(body or {}))
return JSONResponse(content={
"observation": obs.model_dump(),
"reward": obs.reward,
"done": obs.done,
})
@app.post("/step")
async def step_endpoint(req):
body = await req.json()
action_body = body.get("action", body) if isinstance(body, dict) else body
action = APIShiftAction.model_validate(action_body)
obs = _env.step(action)
return JSONResponse(content={
"observation": obs.model_dump(),
"reward": obs.reward,
"done": obs.done,
})
@app.get("/state")
async def state_endpoint():
return JSONResponse(content=_env.state.model_dump())
@app.get("/health")
async def health():
return {"status": "healthy"}
# ---------------------------------------------------------------------
# Cross-origin support so the env is browseable from anywhere
# ---------------------------------------------------------------------
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------
# APIShift-specific endpoints (additive, do not override OpenEnv routes)
# ---------------------------------------------------------------------
@app.get("/tasks", tags=["APIShift"])
async def tasks():
"""List available scenarios (real + synthetic). Phase 2 deep validator
expects this endpoint."""
return {"tasks": list_tasks()}
@app.get("/program", tags=["APIShift"])
async def program():
"""Read the Manager's operating manual (apishift_program.md)."""
path = "apishift_program.md"
if not os.path.exists(path):
return JSONResponse(status_code=404, content={"error": "program file not found"})
with open(path, "r", encoding="utf-8") as f:
return {"path": path, "content": f.read()}
@app.get("/lessons", tags=["APIShift"])
async def lessons():
"""Read the markdown memory artifact (lessons.md)."""
path = "lessons.md"
if not os.path.exists(path):
return {"path": path, "content": ""}
with open(path, "r", encoding="utf-8") as f:
return {"path": path, "content": f.read()}
@app.get("/curriculum", tags=["APIShift"])
async def curriculum():
"""Read the adaptive curriculum config (curriculum.md)."""
path = "curriculum.md"
if not os.path.exists(path):
return {"path": path, "content": ""}
with open(path, "r", encoding="utf-8") as f:
return {"path": path, "content": f.read()}
def _annotate_step(command: str, obs) -> str:
"""Build a short human readable annotation for one step from the
current observation. Used by the episode transcript panel so each
step shows what the specialist actually did."""
if command == "dispatch_diff":
n = len(obs.detected_changes) if obs.detected_changes else 0
if n == 0:
return "DiffSpecialist found no breaking changes"
ctype = obs.detected_changes[0].change_type if obs.detected_changes else ""
return f"DiffSpecialist found {n} breaking change{'s' if n != 1 else ''}{f', first: {ctype}' if ctype else ''}"
if command == "classify_impact":
return "Manager classified blocking vs non blocking changes"
if command == "dispatch_patch":
n = len(obs.generated_patches) if obs.generated_patches else 0
last = obs.generated_patches[-1] if obs.generated_patches else None
if last is not None:
cid = getattr(last, "targets_change_id", "")
return f"PatchSpecialist generated patch {n} for {cid}"
return f"PatchSpecialist generated {n} patches"
if command == "dispatch_test":
tr = obs.last_test_result
if tr is None:
return "TestSpecialist returned no result"
return f"TestSpecialist {tr.passed} of {tr.total} tests pass"
if command == "dispatch_rollback":
rb = obs.rollback_plan
if rb is None:
return "RollbackPlan not produced"
n = len(rb.reversal_steps) if hasattr(rb, "reversal_steps") and rb.reversal_steps else 0
return f"RollbackPlan with {n} reversal step{'s' if n != 1 else ''}"
if command == "submit":
if obs.quality_score >= 0.85:
return f"FIXED, judge verification RESOLVED, final score {obs.quality_score:.2f}"
return f"Episode submitted, final score {obs.quality_score:.2f}"
if command == "inspect":
return "Manager inspected scenario or file"
if command == "read_memory":
n = len(obs.memory_hits) if obs.memory_hits else 0
return f"Retrieved {n} relevant lesson{'s' if n != 1 else ''} from lessons.md"
return ""
@app.post("/run_demo", tags=["APIShift"])
async def run_demo(req: dict):
"""Run an optimal-plan episode in one HTTP call and return the trace.
Used by the web UI to demo a full migration without juggling WebSocket
state in the browser. Returns the per-step reward, an annotation per
step explaining what the specialist did, and the final component
breakdown so the UI can render the bars and the transcript.
"""
task_id = (req or {}).get("task_id")
env = APIShiftEnvironment()
obs0 = env.reset(task_id=task_id)
plan = [
{"command": "dispatch_diff", "rationale": "detect breaking changes"},
{"command": "dispatch_patch", "payload": {"change_id": "ch_001"},
"rationale": "patch ch_001"},
{"command": "dispatch_test", "rationale": "verify backward compat"},
{"command": "dispatch_rollback", "rationale": "produce rollback plan"},
{"command": "submit", "rationale": "finalize migration"},
]
steps = []
last_obs = obs0
for i, action_dict in enumerate(plan, 1):
action = APIShiftAction.model_validate(action_dict)
last_obs = env.step(action)
steps.append({
"step": i,
"command": action.command,
"reward": float(last_obs.reward) if last_obs.reward is not None else 0.0,
"quality_score": float(last_obs.quality_score),
"done": bool(last_obs.done),
"annotation": _annotate_step(action.command, last_obs),
})
if last_obs.done:
break
n_changes = len(obs0.detected_changes) if obs0.detected_changes else 0
if last_obs.quality_score >= 0.85:
verdict = "RESOLVED"
elif last_obs.quality_score >= 0.5:
verdict = "PARTIAL"
else:
verdict = "FAILED"
return {
"scenario": {
"scenario_id": obs0.scenario_id,
"task_description": obs0.task_description,
"framework": obs0.framework,
"language": obs0.language,
"v1_spec_summary": obs0.v1_spec_summary,
"v2_spec_summary": obs0.v2_spec_summary,
"n_breaking_changes": n_changes,
},
"steps": steps,
"final_score": steps[-1]["quality_score"] if steps else 0.0,
"component_rewards": dict(env.state.component_rewards) if env.state.component_rewards else {},
"verdict": verdict,
"n_steps": len(steps),
}
# ---------------------------------------------------------------------
# Stateful HumanAgent sessions, used by the playable HumanAgent panel
# ---------------------------------------------------------------------
# The OpenEnv contract makes /reset and /step stateless (one env per request).
# The HumanAgent UI needs a multi step session, so we maintain an in memory
# dict keyed by session_id with a 15 minute TTL. Capped at 50 sessions.
import time
import secrets
_SESSIONS: dict = {} # session_id -> {"env": APIShiftEnvironment, "history": [...], "last_obs": ..., "ts": float}
_SESSION_TTL = 15 * 60 # 15 minutes
_SESSION_CAP = 50
def _gc_sessions():
"""Drop sessions older than TTL, and enforce the cap."""
now = time.time()
stale = [sid for sid, s in _SESSIONS.items() if now - s["ts"] > _SESSION_TTL]
for sid in stale:
_SESSIONS.pop(sid, None)
if len(_SESSIONS) > _SESSION_CAP:
# drop oldest
oldest = sorted(_SESSIONS.items(), key=lambda kv: kv[1]["ts"])[: len(_SESSIONS) - _SESSION_CAP]
for sid, _ in oldest:
_SESSIONS.pop(sid, None)
def _serialize_obs(obs) -> dict:
"""Trim observation to UI friendly fields."""
if obs is None:
return {}
return {
"scenario_id": obs.scenario_id,
"task_description": obs.task_description,
"framework": obs.framework,
"language": obs.language,
"v1_spec_summary": obs.v1_spec_summary,
"v2_spec_summary": obs.v2_spec_summary,
"n_detected_changes": len(obs.detected_changes) if obs.detected_changes else 0,
"n_generated_patches": len(obs.generated_patches) if obs.generated_patches else 0,
"test_passed": (obs.last_test_result.passed if obs.last_test_result else None),
"test_total": (obs.last_test_result.total if obs.last_test_result else None),
"rollback_present": obs.rollback_plan is not None,
"quality_score": float(obs.quality_score),
"steps_taken": int(obs.steps_taken),
"max_steps": int(obs.max_steps),
"available_commands": list(obs.available_commands) if obs.available_commands else [],
"message": obs.message or "",
"last_action_error": obs.last_action_error,
"reward": float(obs.reward) if obs.reward is not None else 0.0,
"done": bool(obs.done),
}
@app.post("/session/reset", tags=["APIShift"])
async def session_reset(req: dict):
"""Begin or restart a HumanAgent session.
Body:
task_id optional, scenario id to load
session_id optional, reuse an existing session (else a fresh one is created)
Returns the session_id, the initial observation, and the action history (empty).
"""
_gc_sessions()
body = req or {}
sid = body.get("session_id") or secrets.token_urlsafe(12)
task_id = body.get("task_id")
env = APIShiftEnvironment()
obs = env.reset(task_id=task_id)
_SESSIONS[sid] = {
"env": env,
"history": [],
"last_obs": obs,
"ts": time.time(),
"task_id": obs.scenario_id,
}
return {
"session_id": sid,
"task_id": obs.scenario_id,
"observation": _serialize_obs(obs),
"history": [],
"step_count": 0,
"status": "Reset",
}
@app.post("/session/step", tags=["APIShift"])
async def session_step(req: dict):
"""Execute one action against a HumanAgent session.
Body:
session_id required
action APIShiftAction body, or just {"command": "...", "rationale": "..."}
Returns the resulting observation, the updated history, and step count.
"""
body = req or {}
sid = body.get("session_id")
if not sid or sid not in _SESSIONS:
return JSONResponse(status_code=404, content={"error": "session not found, call /session/reset first"})
sess = _SESSIONS[sid]
sess["ts"] = time.time()
action_dict = body.get("action") or body
if "command" not in action_dict:
return JSONResponse(status_code=400, content={"error": "action must include a command"})
try:
action = APIShiftAction.model_validate(action_dict)
except Exception as e:
return JSONResponse(status_code=400, content={"error": f"invalid action: {e}"})
obs = sess["env"].step(action)
sess["last_obs"] = obs
entry = {
"step": len(sess["history"]) + 1,
"command": action.command,
"rationale": action.rationale,
"reward": float(obs.reward) if obs.reward is not None else 0.0,
"quality_score": float(obs.quality_score),
"done": bool(obs.done),
"annotation": _annotate_step(action.command, obs),
}
sess["history"].append(entry)
return {
"session_id": sid,
"observation": _serialize_obs(obs),
"step_entry": entry,
"history": sess["history"],
"step_count": len(sess["history"]),
"status": "Done" if obs.done else "Stepping",
}
@app.get("/session/state", tags=["APIShift"])
async def session_state(session_id: str):
"""Return the current state of a HumanAgent session."""
sid = session_id
if not sid or sid not in _SESSIONS:
return JSONResponse(status_code=404, content={"error": "session not found"})
sess = _SESSIONS[sid]
sess["ts"] = time.time()
obs = sess["last_obs"]
return {
"session_id": sid,
"task_id": sess.get("task_id"),
"observation": _serialize_obs(obs),
"history": sess["history"],
"step_count": len(sess["history"]),
"status": "Done" if (obs and obs.done) else ("Stepping" if sess["history"] else "Reset"),
}
# ---------------------------------------------------------------------
# Web UI at "/" and "/web"
# ---------------------------------------------------------------------
_DASHBOARD_HTML = """
An OpenEnv environment where LLM agents learn to migrate code across breaking API contract changes. We trained a Manager on real Stripe, GitHub, Twilio, Slack, and OpenAI version diffs and watched it improve through GRPO.
Can a 7B model learn to migrate 415 real API breaking changes? Run the demo below to see what we trained, or skip to The Story to see the journey from cold start to first light.
Standard OpenEnv contract: reset, step, state over HTTP, plus a stateful WebSocket session at /ws for multi step episodes. Browse the full OpenEnv API contract.
API vendors ship breaking changes every quarter. There is no shared training ground for an LLM to learn the recurring skill of safe migration.
The Impact
One to three weeks of senior engineer time per migration. Same teams hit the same class of problem 18 months later, because nobody captured the lessons.
Our Solution
An OpenEnv environment with multi agent dispatch, persistent memory, adaptive curriculum, and a five component anti hacking reward. The trained Manager you see in the demo is proof the environment works.
...
Demo Scenarios
5
API Providers
Qwen2.5-7B
Base Model + LoRA
GRPO
RL Method
Try a live episode
Pick a scenario, hit run, and watch the Manager call its specialists in real time. Each step shows the per component reward breakdown.
Pick a scenario
v1 spec, abridged
select a task to see v1
v2 spec, abridged
select a task to see v2
Live episode
No episode running. Pick a scenario above and hit run.
Reward breakdown, per component
Breaking change detection (33%)0.00
Migration patch correctness (28%)0.00
Backward compat preservation (24%)0.00
Rollback plan completeness (10%)0.00
Simplicity bonus (5%)0.00
Final score: --
Episode transcript with findings
No episode run yet
Run the optimal plan above to see a step by step transcript with what each specialist did.
Key findings (this session)
Episodes run: 0
Success rate: --
Average score: --
Average steps to fix: --
Human Agent mode
Take the Manager's seat. Reset the env to a scenario, type one action at a time as JSON, click Step, and watch the observation update on the right. This is the same OpenEnv contract that programmatic agents call.
No observation yet. Click Reset Environment to start.
Action History
No actions taken yet
How it works
The Manager agent receives one scenario per episode. It calls four specialist agents in sequence, gets scored on five
independent reward components, and writes a markdown lesson at the end so the next episode starts smarter.
The Manager dispatches to DiffSpecialist, PatchSpecialist, TestSpecialist and RollbackSpecialist. Their outputs are scored by five independent reward components. The MemoryAgent writes a structured lesson, the CurriculumAgent picks the next scenario, and the loop continues.
Every action above flows through the OpenEnv contract. The web demo above is just a thin wrapper around the same /run_demo endpoint that judges and external clients call programmatically.
Reward design, made hard to game
Five independent verifiers. The Manager cannot read its own reward. Skipping rollback triggers a hard penalty.
Repeated dispatches do not stack. Memory is write protected from the Manager. Anti hacking story is documented in detail in
REWARD_DESIGN.md.
total_reward =
0.33 * breaking_change_detection_score # F1 over labeled breaking changes
+ 0.28 * migration_patch_correctness # template match per change_type
+ 0.24 * backward_compat_preservation # TestSpecialist pass rate
+ 0.10 * rollback_plan_completeness # rollback verifier
+ 0.05 * simplicity_bonus # fewer steps wins
- 0.10 if dispatch_rollback was never called
clamped to (0.01, 0.99)
The Story, how the environment and the agent improved together
We trained two runs. The journey from the first to the second is the most useful thing about this submission. The environment is what came out of it.
Act 1, the cold start
First GRPO run with the obvious config. num_generations=4, temperature 1.0, single tier reward. Within ten steps the reward locked at 0.01. Model output prose instead of JSON. Reward variance was zero. Gradient norm was zero. The model was not learning.
Act 2, the diagnosis
Reward had no gradation between "no JSON at all" and "some JSON but wrong format". All four completions in a batch landed at the same minimum. GRPO needs variance within the batch to compute advantages. We had none.
Act 3, the reward fights back
Three changes. Added a partial credit layer (0.02 per valid JSON command, 0.02 for ending with submit). Bumped num_generations from 4 to 8. Bumped temperature 1.0 to 1.2. Dry run reward standard deviation jumped from 0.0 to 0.12.
Act 4, first light
By step 100, reward average 0.175. By step 200, 0.20. Peak phase around step 900, averaging 0.245 with a single batch peak of 0.434. Forty four percent of the steps in the early phase fired real gradient updates. The Manager had learned the JSON workflow.
What the Manager learned
Output JSON action blobs, never prose
Always call dispatch_diff before any patch
Patch each detected breaking change by its real change_id, not a placeholder
Always call dispatch_rollback before submit (the hard penalty taught it this)
End with submit, never leave the episode hanging
What we learned, from the Manager's failures
Cold start GRPO needs partial credit, otherwise gradient is zero forever
num_generations=4 is the floor for structured output, eight is safer
Temperature 1.0 collapses output diversity, 1.2 keeps it
Per component reward decomposition belongs in the trainer state, not just the summary
Environment must reward intermediate format compliance, not just final correctness
The training infrastructure co-evolved with the agent. The reward function we ship today is the one the agent's failures forced us to design.
Breaking change types the environment can inject
The mutator in scenarios/layer2_synthetic/mutator.py can apply any of these to a real spec from scenarios/layer1_real/, producing infinite novel scenarios for training.
Change type
Real example
What the agent must produce
field_renamed
Stripe customer_email to customer_contact_email
Replace field references in request body and response handler
endpoint_removed
/v1/old_endpoint deleted in v2
Update URL and migrate request shape to the replacement endpoint
parameter_added_required
New required idempotency_key
Add the parameter at every call site
parameter_removed
Removed legacy_format
Drop the parameter from every call site
type_changed
amount int to string
Wrap calls in str / int conversion at boundary
auth_scheme_changed
GitHub PAT to Bearer
Swap the Authorization header construction
response_field_renamed
Twilio from to from_phone
Update response field accessors
enum_value_removed
Slack presence=auto removed
Map old values to new ones in client wrapper
multi_change
Two or three of the above in one episode
Diff first, classify all, patch each by id
Training results
Trained on a single A40 GPU with TRL GRPO and LoRA on Qwen2.5-7B. Plots below summarize the run.
Reward curve over training
Reward by training phase (early / mid / late)
Reward components stacked over training
Reward density: early training vs late training
"""
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def root():
return HTMLResponse(content=_DASHBOARD_HTML)
@app.get("/web", response_class=HTMLResponse, include_in_schema=False)
async def web():
return HTMLResponse(content=_DASHBOARD_HTML)
# Static asset route for plots, served from outputs/ at the repo root
@app.get("/assets/{filename}", include_in_schema=False)
async def assets(filename: str):
"""Serve plot images from outputs/. Used by the web UI plot section."""
from fastapi.responses import FileResponse
safe = os.path.basename(filename)
candidate = os.path.join("outputs", safe)
if not os.path.exists(candidate):
return JSONResponse(status_code=404, content={"error": "asset not found", "path": candidate})
return FileResponse(candidate)
# ---------------------------------------------------------------------
# Server entry point (for `uv run server` and `python -m server.app`)
# ---------------------------------------------------------------------
def main() -> None:
"""Start uvicorn on the standard OpenEnv port."""
import uvicorn
uvicorn.run(
"server.app:app",
host=os.getenv("HOST", "0.0.0.0"),
port=int(os.getenv("PORT", "7860")),
log_level="info",
)
if __name__ == "__main__":
main()