|
| 1 | +"""Example demonstrating deferred-init (warm-pool) mode for the agent server. |
| 2 | +
|
| 3 | +In warm-pool deployments, server pods are pre-warmed before a user is matched |
| 4 | +to one. The pod boots with ``OH_DEFERRED_INIT=true``: stateless services |
| 5 | +(VSCode, tool preload, etc.) start as normal, but all ``/api/*`` routes return |
| 6 | +503 until ``POST /api/init`` delivers the runtime configuration (credentials, |
| 7 | +workspace paths, session keys). |
| 8 | +
|
| 9 | +The orchestrator authenticates the init call with the server's bootstrap secret |
| 10 | +key (``OH_SECRET_KEY`` / ``X-Init-API-Key``), which it already holds for |
| 11 | +encryption purposes. |
| 12 | +
|
| 13 | +Lifecycle demonstrated here: |
| 14 | + 1. Server starts in dormant mode. |
| 15 | + 2. ``GET /api/init`` reports state=dormant. |
| 16 | + 3. ``GET /api/conversations`` returns 503 (dormant gate is active). |
| 17 | + 4. ``POST /api/init`` delivers runtime config → server transitions to ready. |
| 18 | + 5. ``GET /api/init`` reports state=ready. |
| 19 | + 6. A conversation runs normally on the now-ready server. |
| 20 | +""" |
| 21 | + |
| 22 | +import os |
| 23 | +import tempfile |
| 24 | +import time |
| 25 | +from uuid import UUID |
| 26 | + |
| 27 | +import httpx |
| 28 | +from scripts.utils import ManagedAPIServer |
| 29 | + |
| 30 | +from openhands.sdk import get_logger |
| 31 | + |
| 32 | + |
| 33 | +logger = get_logger(__name__) |
| 34 | + |
| 35 | +# ── LLM config ────────────────────────────────────────────────────────────── |
| 36 | + |
| 37 | +api_key = os.getenv("LLM_API_KEY") |
| 38 | +assert api_key is not None, "LLM_API_KEY environment variable is not set." |
| 39 | +llm_model = os.getenv("LLM_MODEL", "gpt-5.5") |
| 40 | +llm_base_url = os.getenv("LLM_BASE_URL") |
| 41 | + |
| 42 | +# The orchestrator knows this key before the pod is matched to a user. |
| 43 | +# It's used to authenticate POST /api/init and as the encryption secret. |
| 44 | +BOOTSTRAP_SECRET_KEY = "demo-warm-pool-bootstrap-key-32b!" |
| 45 | + |
| 46 | +# ── Server lifecycle ───────────────────────────────────────────────────────── |
| 47 | + |
| 48 | +with ManagedAPIServer( |
| 49 | + port=8003, |
| 50 | + extra_env={ |
| 51 | + "OH_DEFERRED_INIT": "true", |
| 52 | + "OH_SECRET_KEY": BOOTSTRAP_SECRET_KEY, |
| 53 | + "TMUX_TMPDIR": "/tmp/oh-tmux-deferred", |
| 54 | + }, |
| 55 | +) as server: |
| 56 | + client = httpx.Client(base_url=server.base_url, timeout=120.0) |
| 57 | + |
| 58 | + try: |
| 59 | + # ── 1. Confirm dormant state ───────────────────────────────────────── |
| 60 | + logger.info("\n" + "=" * 60) |
| 61 | + logger.info("📊 Step 1: checking initial (dormant) state") |
| 62 | + logger.info("=" * 60) |
| 63 | + |
| 64 | + resp = client.get("/api/init") |
| 65 | + assert resp.status_code == 200, f"GET /api/init failed: {resp.text}" |
| 66 | + init_status = resp.json() |
| 67 | + assert init_status["state"] == "dormant", ( |
| 68 | + f"Expected dormant, got: {init_status['state']}" |
| 69 | + ) |
| 70 | + logger.info(f"✅ Server is dormant — {init_status}") |
| 71 | + |
| 72 | + # ── 2. Verify the dormant gate blocks /api/* ───────────────────────── |
| 73 | + logger.info("\n" + "=" * 60) |
| 74 | + logger.info("🚧 Step 2: dormant gate returns 503 on /api/conversations") |
| 75 | + logger.info("=" * 60) |
| 76 | + |
| 77 | + resp = client.get("/api/conversations") |
| 78 | + assert resp.status_code == 503, ( |
| 79 | + f"Expected 503 from dormant gate, got {resp.status_code}" |
| 80 | + ) |
| 81 | + logger.info("✅ /api/conversations correctly returns 503 while dormant") |
| 82 | + |
| 83 | + # ── 3. Activate via POST /api/init ─────────────────────────────────── |
| 84 | + logger.info("\n" + "=" * 60) |
| 85 | + logger.info("🚀 Step 3: activating server via POST /api/init") |
| 86 | + logger.info("=" * 60) |
| 87 | + |
| 88 | + temp_workspace_dir = tempfile.mkdtemp(prefix="deferred_init_demo_") |
| 89 | + |
| 90 | + # In a real warm-pool deployment, credentials that the server shouldn't |
| 91 | + # have at cold-start (e.g., the user's LLM API key) would arrive here. |
| 92 | + llm_env: dict[str, str] = {"LLM_API_KEY": api_key} |
| 93 | + if llm_base_url: |
| 94 | + llm_env["LLM_BASE_URL"] = llm_base_url |
| 95 | + |
| 96 | + init_body: dict = { |
| 97 | + # Pass user credentials into the server's environment. |
| 98 | + "env": llm_env, |
| 99 | + } |
| 100 | + |
| 101 | + resp = client.post( |
| 102 | + "/api/init", |
| 103 | + json=init_body, |
| 104 | + headers={"X-Init-API-Key": BOOTSTRAP_SECRET_KEY}, |
| 105 | + ) |
| 106 | + assert resp.status_code == 200, f"POST /api/init failed: {resp.text}" |
| 107 | + init_status = resp.json() |
| 108 | + assert init_status["state"] == "ready", ( |
| 109 | + f"Expected ready after init, got: {init_status['state']}" |
| 110 | + ) |
| 111 | + logger.info(f"✅ Server is now ready — {init_status}") |
| 112 | + |
| 113 | + # ── 4. Confirm ready via GET /api/init ─────────────────────────────── |
| 114 | + resp = client.get("/api/init") |
| 115 | + assert resp.status_code == 200 |
| 116 | + assert resp.json()["state"] == "ready" |
| 117 | + logger.info("✅ GET /api/init confirms ready state") |
| 118 | + |
| 119 | + # ── 5. Run a conversation on the now-ready server ──────────────────── |
| 120 | + logger.info("\n" + "=" * 60) |
| 121 | + logger.info("🤖 Step 5: running a conversation on the ready server") |
| 122 | + logger.info("=" * 60) |
| 123 | + |
| 124 | + llm_config: dict[str, str] = {"model": llm_model, "api_key": api_key} |
| 125 | + if llm_base_url: |
| 126 | + llm_config["base_url"] = llm_base_url |
| 127 | + |
| 128 | + start_request: dict = { |
| 129 | + "agent": { |
| 130 | + "kind": "Agent", |
| 131 | + "llm": llm_config, |
| 132 | + "tools": [], |
| 133 | + }, |
| 134 | + "workspace": {"working_dir": temp_workspace_dir}, |
| 135 | + "initial_message": { |
| 136 | + "role": "user", |
| 137 | + "content": [{"type": "text", "text": "Reply with just the number 42."}], |
| 138 | + "run": True, |
| 139 | + }, |
| 140 | + } |
| 141 | + |
| 142 | + resp = client.post("/api/conversations", json=start_request) |
| 143 | + assert resp.status_code == 201, f"Start conversation failed: {resp.text}" |
| 144 | + conversation_id = UUID(resp.json()["id"]) |
| 145 | + logger.info(f"✅ Conversation started: {conversation_id}") |
| 146 | + |
| 147 | + # Poll until the agent finishes. |
| 148 | + max_wait = 120 |
| 149 | + elapsed = 0 |
| 150 | + execution_status = "unknown" |
| 151 | + while elapsed < max_wait: |
| 152 | + resp = client.get(f"/api/conversations/{conversation_id}") |
| 153 | + assert resp.status_code == 200 |
| 154 | + data = resp.json() |
| 155 | + execution_status = data.get("execution_status", "unknown") |
| 156 | + if execution_status in ("stopped", "paused", "error"): |
| 157 | + break |
| 158 | + logger.info(f" status: {execution_status} ({elapsed}s elapsed)") |
| 159 | + time.sleep(2) |
| 160 | + elapsed += 2 |
| 161 | + |
| 162 | + logger.info(f"✅ Conversation finished — status: {execution_status}") |
| 163 | + assert execution_status in ("stopped", "paused"), ( |
| 164 | + f"Unexpected final status: {execution_status}" |
| 165 | + ) |
| 166 | + |
| 167 | + resp = client.get(f"/api/conversations/{conversation_id}/agent_final_response") |
| 168 | + if resp.status_code == 200: |
| 169 | + agent_response = resp.json().get("response", "") |
| 170 | + logger.info(f" Agent response: {agent_response!r}") |
| 171 | + |
| 172 | + # Collect cost metrics. |
| 173 | + accumulated_cost = 0.0 |
| 174 | + resp = client.get(f"/api/conversations/{conversation_id}") |
| 175 | + if resp.status_code == 200: |
| 176 | + stats = resp.json().get("stats") or {} |
| 177 | + usage_to_metrics = stats.get("usage_to_metrics") or {} |
| 178 | + accumulated_cost = sum( |
| 179 | + m.get("accumulated_cost", 0.0) for m in usage_to_metrics.values() |
| 180 | + ) |
| 181 | + |
| 182 | + client.delete(f"/api/conversations/{conversation_id}") |
| 183 | + logger.info(" Conversation deleted") |
| 184 | + |
| 185 | + logger.info("\n" + "=" * 60) |
| 186 | + logger.info("🎉 Deferred-init example completed successfully!") |
| 187 | + logger.info("=" * 60) |
| 188 | + |
| 189 | + print(f"EXAMPLE_COST: {accumulated_cost}") |
| 190 | + |
| 191 | + finally: |
| 192 | + client.close() |
0 commit comments