appworld-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,35 @@
1
+ """App World SDK — lightweight client for RL & Eval on the App World platform.
2
+
3
+ Install: ``pip install appworld-sdk``
4
+
5
+ Dependencies: requests, numpy, Pillow, gymnasium (no platform internals).
6
+ """
7
+
8
+ from appworld_sdk.agent import BaseAgent
9
+ from appworld_sdk.client import (
10
+ AppWorldClient,
11
+ LocalEvalBatchResult,
12
+ LocalEvalResult,
13
+ RunResult,
14
+ )
15
+ from appworld_sdk.env import RemoteAppWorldEnv, RemoteAppWorldEvalEnv
16
+ from appworld_sdk.errors import (
17
+ AppWorldAPIError,
18
+ AppWorldError,
19
+ EnvironmentNotReady,
20
+ SessionExpired,
21
+ )
22
+
23
+ __all__ = [
24
+ "AppWorldClient",
25
+ "BaseAgent",
26
+ "RemoteAppWorldEnv",
27
+ "RemoteAppWorldEvalEnv",
28
+ "RunResult",
29
+ "LocalEvalResult",
30
+ "LocalEvalBatchResult",
31
+ "AppWorldError",
32
+ "AppWorldAPIError",
33
+ "EnvironmentNotReady",
34
+ "SessionExpired",
35
+ ]
appworld_sdk/agent.py ADDED
@@ -0,0 +1,43 @@
1
+ """Base agent protocol for client-side eval loops."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Protocol, runtime_checkable
6
+
7
+ import numpy as np
8
+
9
+
10
+ @runtime_checkable
11
+ class BaseAgent(Protocol):
12
+ """Agent that decides actions based on observations.
13
+
14
+ Users implement this protocol to plug in custom models.
15
+ The SDK never imports any specific LLM provider — that's the
16
+ user's responsibility.
17
+
18
+ Example::
19
+
20
+ class MyAgent:
21
+ def predict(self, *, screenshot, goal, **kw) -> dict:
22
+ # call your own model
23
+ return {"action_type": 0, "x": 0.5, "y": 0.5, ...}
24
+ """
25
+
26
+ def predict(
27
+ self,
28
+ *,
29
+ screenshot: np.ndarray,
30
+ goal: str,
31
+ task_name: str,
32
+ task_description: str,
33
+ app_names: list[str],
34
+ step_index: int,
35
+ max_steps: int,
36
+ history: list[str],
37
+ ) -> dict[str, Any]:
38
+ """Return an action dict.
39
+
40
+ Expected keys: action_type, x, y, text, direction, app_name.
41
+ Optional key: description (used for history logging).
42
+ """
43
+ ...
appworld_sdk/client.py ADDED
@@ -0,0 +1,534 @@
1
+ """HTTP client for the App World platform.
2
+
3
+ This is a pure API client — it knows nothing about tasks, adapters,
4
+ rewards, or LLM providers. All heavy lifting happens on the platform
5
+ side; the client just sends HTTP requests and returns results.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import logging
12
+ import time
13
+ from dataclasses import dataclass, field
14
+ from io import BytesIO
15
+ from typing import Any
16
+
17
+ import numpy as np
18
+ import requests
19
+ from PIL import Image
20
+
21
+ from appworld_sdk.agent import BaseAgent
22
+ from appworld_sdk.env import RemoteAppWorldEnv, RemoteAppWorldEvalEnv
23
+ from appworld_sdk.errors import (
24
+ AppWorldAPIError,
25
+ EnvironmentNotReady,
26
+ SessionExpired,
27
+ )
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def _decode_screenshot(data_url: str) -> np.ndarray:
33
+ """Decode a data:image/... URL into an RGB numpy array."""
34
+ _, payload = data_url.split(",", 1)
35
+ binary = base64.b64decode(payload)
36
+ return np.array(Image.open(BytesIO(binary)).convert("RGB"))
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Result data classes
41
+ # ---------------------------------------------------------------------------
42
+
43
+
44
+ @dataclass
45
+ class RunResult:
46
+ id: str
47
+ name: str
48
+ status: str
49
+ type: str
50
+ environment_id: str
51
+ success_rate: float | None
52
+ avg_steps: float | None
53
+ results: list[dict[str, Any]]
54
+ raw: dict[str, Any]
55
+
56
+
57
+ @dataclass
58
+ class LocalEvalResult:
59
+ """Result of a single-task client-side eval."""
60
+
61
+ task_name: str
62
+ status: str
63
+ steps: int
64
+ reward: float
65
+ history: list[str]
66
+ terminated: bool
67
+ truncated: bool
68
+
69
+
70
+ @dataclass
71
+ class LocalEvalBatchResult:
72
+ """Aggregated result of a multi-task local eval."""
73
+
74
+ task_results: list[LocalEvalResult] = field(default_factory=list)
75
+
76
+ @property
77
+ def success_rate(self) -> float:
78
+ if not self.task_results:
79
+ return 0.0
80
+ return sum(1 for r in self.task_results if r.status == "completed") / len(
81
+ self.task_results
82
+ )
83
+
84
+ @property
85
+ def avg_steps(self) -> float:
86
+ if not self.task_results:
87
+ return 0.0
88
+ return sum(r.steps for r in self.task_results) / len(self.task_results)
89
+
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # Client
93
+ # ---------------------------------------------------------------------------
94
+
95
+
96
+ class AppWorldClient:
97
+ """Thin API client for the App World platform.
98
+
99
+ Usage::
100
+
101
+ client = AppWorldClient(api_key="sk-xxx", base_url="https://api.appworld.dev")
102
+
103
+ # Browse catalog
104
+ tasks = client.list_tasks()
105
+
106
+ # Create environment (allocates device resources)
107
+ env_info = client.create_environment(
108
+ task_ids=["FennoteCreateNote", "FennoteDeleteNote"],
109
+ )
110
+ env_id = env_info["id"]
111
+
112
+ # Get a Gymnasium-compatible env (bound to environment, NOT to a task)
113
+ env = client.make_env(env_id=env_id, env_type="eval")
114
+
115
+ # Run multiple tasks on the same environment
116
+ for task in ["FennoteCreateNote", "FennoteDeleteNote"]:
117
+ obs, info = env.reset(task_name=task)
118
+ done = False
119
+ while not done:
120
+ action = my_agent.predict(screenshot=obs["screenshot"], goal=obs["goal"], ...)
121
+ obs, reward, terminated, truncated, info = env.step(action)
122
+ done = terminated or truncated
123
+
124
+ env.close()
125
+ """
126
+
127
+ def __init__(
128
+ self,
129
+ api_key: str,
130
+ base_url: str = "http://127.0.0.1:8000",
131
+ timeout: float = 60.0,
132
+ ):
133
+ self.api_key = api_key
134
+ self.base_url = base_url.rstrip("/")
135
+ self.timeout = timeout
136
+
137
+ @property
138
+ def headers(self) -> dict[str, str]:
139
+ return {
140
+ "Authorization": f"Bearer {self.api_key}",
141
+ "Content-Type": "application/json",
142
+ }
143
+
144
+ # ------------------------------------------------------------------
145
+ # HTTP helpers
146
+ # ------------------------------------------------------------------
147
+
148
+ def _raise_for_status(self, response: requests.Response) -> None:
149
+ if response.ok:
150
+ return
151
+ detail = ""
152
+ try:
153
+ body = response.json()
154
+ detail = body.get("detail", "")
155
+ except Exception:
156
+ detail = response.text[:200]
157
+ if response.status_code == 503:
158
+ raise EnvironmentNotReady("unknown", detail=detail)
159
+ if response.status_code == 410:
160
+ raise SessionExpired("unknown", detail=detail)
161
+ raise AppWorldAPIError(
162
+ detail or response.reason or "API error",
163
+ status_code=response.status_code,
164
+ detail=detail,
165
+ )
166
+
167
+ def _get(self, path: str, params: dict[str, Any] | None = None) -> Any:
168
+ response = requests.get(
169
+ f"{self.base_url}{path}",
170
+ headers=self.headers,
171
+ params=params,
172
+ timeout=self.timeout,
173
+ )
174
+ self._raise_for_status(response)
175
+ return response.json()
176
+
177
+ def _post(self, path: str, payload: dict[str, Any]) -> Any:
178
+ response = requests.post(
179
+ f"{self.base_url}{path}",
180
+ headers=self.headers,
181
+ json=payload,
182
+ timeout=self.timeout,
183
+ )
184
+ self._raise_for_status(response)
185
+ return response.json()
186
+
187
+ def _delete(self, path: str) -> Any:
188
+ response = requests.delete(
189
+ f"{self.base_url}{path}",
190
+ headers=self.headers,
191
+ timeout=self.timeout,
192
+ )
193
+ self._raise_for_status(response)
194
+ return response.json()
195
+
196
+ # ------------------------------------------------------------------
197
+ # Catalog
198
+ # ------------------------------------------------------------------
199
+
200
+ def list_apps(self, **filters: Any) -> list[dict[str, Any]]:
201
+ return self._get("/api/v1/apps", params=filters)["items"]
202
+
203
+ def list_tasks(self, **filters: Any) -> list[dict[str, Any]]:
204
+ return self._get("/api/v1/tasks", params=filters)["items"]
205
+
206
+ def get_task(self, task_id: str) -> dict[str, Any]:
207
+ return self._get(f"/api/v1/tasks/{task_id}")
208
+
209
+ # ------------------------------------------------------------------
210
+ # Environments
211
+ # ------------------------------------------------------------------
212
+
213
+ def list_environments(self, **filters: Any) -> list[dict[str, Any]]:
214
+ return self._get("/api/v1/environments", params=filters)["items"]
215
+
216
+ def create_environment(
217
+ self,
218
+ task_ids: list[str],
219
+ name: str | None = None,
220
+ ) -> dict[str, Any]:
221
+ payload = {"task_ids": task_ids, "name": name or "sdk-environment"}
222
+ return self._post("/api/v1/environments", payload)
223
+
224
+ def get_environment(self, env_id: str) -> dict[str, Any]:
225
+ return self._get(f"/api/v1/environments/{env_id}")
226
+
227
+ def delete_environment(self, env_id: str) -> dict[str, Any]:
228
+ return self._delete(f"/api/v1/environments/{env_id}")
229
+
230
+ def get_environment_status(self, env_id: str) -> dict[str, Any]:
231
+ return self._get(f"/api/v1/environments/{env_id}/status")
232
+
233
+ def stop_environment(self, env_id: str) -> dict[str, Any]:
234
+ return self._post(f"/api/v1/environments/{env_id}/stop", {})
235
+
236
+ def restart_environment(self, env_id: str) -> dict[str, Any]:
237
+ return self._post(f"/api/v1/environments/{env_id}/restart", {})
238
+
239
+ # ------------------------------------------------------------------
240
+ # Low-level SDK env endpoints (for advanced usage)
241
+ # ------------------------------------------------------------------
242
+
243
+ def sdk_reset(
244
+ self,
245
+ *,
246
+ env_id: str,
247
+ task_name: str,
248
+ env_type: str = "eval",
249
+ ) -> dict[str, Any]:
250
+ return self._post("/api/v1/sdk/env/reset", {
251
+ "env_id": env_id,
252
+ "task_name": task_name,
253
+ "env_type": env_type,
254
+ })
255
+
256
+ def sdk_step(self, *, session_id: str, action: Any) -> dict[str, Any]:
257
+ return self._post("/api/v1/sdk/env/step", {
258
+ "session_id": session_id,
259
+ "action": action,
260
+ })
261
+
262
+ def sdk_close(self, *, session_id: str) -> dict[str, Any]:
263
+ return self._post("/api/v1/sdk/env/close", {"session_id": session_id})
264
+
265
+ # ------------------------------------------------------------------
266
+ # Gymnasium-compatible remote environment
267
+ # ------------------------------------------------------------------
268
+
269
+ def make_env(
270
+ self,
271
+ *,
272
+ env_id: str,
273
+ env_type: str = "eval",
274
+ ) -> RemoteAppWorldEnv | RemoteAppWorldEvalEnv:
275
+ """Create a Gymnasium-compatible remote environment.
276
+
277
+ The env is bound to an environment (device resources), NOT to a
278
+ specific task. Pass ``task_name`` to ``env.reset()`` to start
279
+ each task.
280
+
281
+ Args:
282
+ env_id: Environment ID from ``create_environment()``.
283
+ env_type: ``"rl"`` or ``"eval"``.
284
+
285
+ Returns:
286
+ RemoteAppWorldEnv (rl) or RemoteAppWorldEvalEnv (eval).
287
+ """
288
+ if env_type == "rl":
289
+ return RemoteAppWorldEnv(
290
+ api_key=self.api_key,
291
+ base_url=self.base_url,
292
+ env_id=env_id,
293
+ )
294
+ if env_type == "eval":
295
+ return RemoteAppWorldEvalEnv(
296
+ api_key=self.api_key,
297
+ base_url=self.base_url,
298
+ env_id=env_id,
299
+ )
300
+ raise ValueError(f"env_type must be 'rl' or 'eval', got '{env_type}'")
301
+
302
+ # ------------------------------------------------------------------
303
+ # Runs (server-side eval)
304
+ # ------------------------------------------------------------------
305
+
306
+ def list_runs(self, **filters: Any) -> list[dict[str, Any]]:
307
+ return self._get("/api/v1/runs", params=filters)["items"]
308
+
309
+ def get_run(self, run_id: str) -> dict[str, Any]:
310
+ return self._get(f"/api/v1/runs/{run_id}")
311
+
312
+ def create_run(
313
+ self,
314
+ environment_id: str,
315
+ run_type: str,
316
+ tasks: list[str],
317
+ name: str | None = None,
318
+ ) -> dict[str, Any]:
319
+ return self._post("/api/v1/runs", {
320
+ "environment_id": environment_id,
321
+ "type": run_type,
322
+ "tasks": tasks,
323
+ "name": name,
324
+ })
325
+
326
+ def wait_for_run(
327
+ self,
328
+ run_id: str,
329
+ poll_interval: float = 0.2,
330
+ timeout: float = 20.0,
331
+ ) -> dict[str, Any]:
332
+ deadline = time.monotonic() + timeout
333
+ while True:
334
+ run = self.get_run(run_id)
335
+ if run["status"] in {"completed", "failed", "stopped"}:
336
+ return run
337
+ if time.monotonic() >= deadline:
338
+ raise TimeoutError(
339
+ f"Run '{run_id}' did not finish within {timeout} seconds"
340
+ )
341
+ time.sleep(poll_interval)
342
+
343
+ def run_eval(
344
+ self,
345
+ env_id: str,
346
+ tasks: list[str],
347
+ model_provider: str,
348
+ model_api_key: str,
349
+ model_name: str | None = None,
350
+ name: str | None = None,
351
+ wait: bool = True,
352
+ poll_interval: float = 0.2,
353
+ timeout: float = 20.0,
354
+ max_steps: int = 15,
355
+ ) -> RunResult:
356
+ """Submit an eval run to the platform (server-side execution).
357
+
358
+ The platform handles LLM calls and environment interactions.
359
+ The model API key is sent to the server for this execution mode.
360
+ """
361
+ payload: dict[str, Any] = {
362
+ "environment_id": env_id,
363
+ "type": "eval",
364
+ "tasks": tasks,
365
+ "name": name,
366
+ "model_provider": model_provider,
367
+ "model_api_key": model_api_key,
368
+ "max_steps": max_steps,
369
+ }
370
+ if model_name:
371
+ payload["model_name"] = model_name
372
+ run = self._post("/api/v1/runs", payload)
373
+ if wait:
374
+ run = self.wait_for_run(
375
+ run["id"], poll_interval=poll_interval, timeout=timeout,
376
+ )
377
+ return self._to_run_result(run)
378
+
379
+ # ------------------------------------------------------------------
380
+ # Local eval (LLM runs on user side, env interactions via API)
381
+ # ------------------------------------------------------------------
382
+
383
+ def run_local_eval(
384
+ self,
385
+ env_id: str,
386
+ tasks: list[str],
387
+ agent: BaseAgent,
388
+ max_steps: int = 15,
389
+ ) -> LocalEvalBatchResult:
390
+ """Local eval: LLM calls happen on the client side.
391
+
392
+ The agent's API key never leaves the local process. The server
393
+ only handles environment interactions (screenshots, actions, state).
394
+
395
+ Args:
396
+ env_id: Environment ID from ``create_environment()``.
397
+ tasks: List of task names to evaluate.
398
+ agent: An object implementing ``BaseAgent.predict()``.
399
+ max_steps: Maximum steps per task.
400
+ """
401
+ if not isinstance(agent, BaseAgent):
402
+ raise TypeError(
403
+ f"agent must implement BaseAgent.predict(), got {type(agent).__name__}"
404
+ )
405
+
406
+ batch = LocalEvalBatchResult()
407
+ for task_name in tasks:
408
+ try:
409
+ result = self._run_local_eval_task(
410
+ env_id=env_id,
411
+ task_name=task_name,
412
+ agent=agent,
413
+ max_steps=max_steps,
414
+ )
415
+ except Exception as exc:
416
+ logger.warning("Task %s failed: %s", task_name, exc)
417
+ result = LocalEvalResult(
418
+ task_name=task_name,
419
+ status="failed",
420
+ steps=0,
421
+ reward=0.0,
422
+ history=[],
423
+ terminated=False,
424
+ truncated=False,
425
+ )
426
+ batch.task_results.append(result)
427
+ return batch
428
+
429
+ def _run_local_eval_task(
430
+ self,
431
+ env_id: str,
432
+ task_name: str,
433
+ agent: BaseAgent,
434
+ max_steps: int,
435
+ ) -> LocalEvalResult:
436
+ """Run a single task with client-side LLM inference."""
437
+ task_info = self.get_task(task_name)
438
+ task_description = task_info.get("description", "")
439
+ app_names = task_info.get("app_names", [])
440
+
441
+ reset_payload = self._post("/api/v1/sdk/env/reset", {
442
+ "env_id": env_id,
443
+ "task_name": task_name,
444
+ "env_type": "eval",
445
+ })
446
+ session_id = reset_payload["session_id"]
447
+ observation = reset_payload["observation"]
448
+ goal = observation.get("goal", task_description)
449
+
450
+ history: list[str] = []
451
+ total_reward = 0.0
452
+ steps_taken = 0
453
+ terminated = False
454
+ truncated = False
455
+
456
+ try:
457
+ for step_index in range(1, max_steps + 1):
458
+ screenshot = _decode_screenshot(observation["screenshot"])
459
+
460
+ action = agent.predict(
461
+ screenshot=screenshot,
462
+ goal=goal,
463
+ task_name=task_name,
464
+ task_description=task_description,
465
+ app_names=app_names,
466
+ step_index=step_index,
467
+ max_steps=max_steps,
468
+ history=history,
469
+ )
470
+
471
+ description = action.get(
472
+ "description", action.get("action_type", "action"),
473
+ )
474
+ history.append(str(description))
475
+
476
+ logger.info(
477
+ "step %d/%d: %s (%.2f, %.2f) %s",
478
+ step_index,
479
+ max_steps,
480
+ action.get("action_type"),
481
+ action.get("x", 0),
482
+ action.get("y", 0),
483
+ description,
484
+ )
485
+
486
+ step_payload = self._post("/api/v1/sdk/env/step", {
487
+ "session_id": session_id,
488
+ "action": action,
489
+ })
490
+
491
+ total_reward = float(step_payload["reward"])
492
+ terminated = bool(step_payload["terminated"])
493
+ truncated = bool(step_payload["truncated"])
494
+ steps_taken = step_index
495
+
496
+ if terminated or truncated:
497
+ break
498
+
499
+ observation = step_payload["observation"]
500
+ goal = observation.get("goal", goal)
501
+
502
+ finally:
503
+ try:
504
+ self._post("/api/v1/sdk/env/close", {"session_id": session_id})
505
+ except Exception:
506
+ pass
507
+
508
+ status = "completed" if terminated or total_reward >= 1.0 else "failed"
509
+ return LocalEvalResult(
510
+ task_name=task_name,
511
+ status=status,
512
+ steps=steps_taken,
513
+ reward=total_reward,
514
+ history=history,
515
+ terminated=terminated,
516
+ truncated=truncated,
517
+ )
518
+
519
+ # ------------------------------------------------------------------
520
+ # Helpers
521
+ # ------------------------------------------------------------------
522
+
523
+ def _to_run_result(self, payload: dict[str, Any]) -> RunResult:
524
+ return RunResult(
525
+ id=payload["id"],
526
+ name=payload["name"],
527
+ status=payload["status"],
528
+ type=payload["type"],
529
+ environment_id=payload["environment_id"],
530
+ success_rate=payload.get("success_rate"),
531
+ avg_steps=payload.get("avg_steps"),
532
+ results=payload.get("tasks", []),
533
+ raw=payload,
534
+ )
appworld_sdk/env.py ADDED
@@ -0,0 +1,194 @@
1
+ """Remote Gymnasium-compatible environments backed by the App World API.
2
+
3
+ The env is bound to an *environment* (device/container resources),
4
+ NOT to a specific task. ``task_name`` is passed at ``reset()`` time,
5
+ so one env object can run multiple tasks sequentially — the typical
6
+ multi-task eval workflow.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ from io import BytesIO
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+ import requests
17
+ from PIL import Image
18
+ from gymnasium import spaces
19
+
20
+ from appworld_sdk.errors import AppWorldAPIError, EnvironmentNotReady, SessionExpired
21
+
22
+
23
+ def _decode_data_url_png(data_url: str) -> np.ndarray:
24
+ _, payload = data_url.split(",", 1)
25
+ binary = base64.b64decode(payload)
26
+ return np.array(Image.open(BytesIO(binary)).convert("RGB"))
27
+
28
+
29
+ def _raise_for_status(response: requests.Response) -> None:
30
+ """Convert HTTP errors to SDK exceptions."""
31
+ if response.ok:
32
+ return
33
+ detail = ""
34
+ try:
35
+ body = response.json()
36
+ detail = body.get("detail", "")
37
+ except Exception:
38
+ detail = response.text[:200]
39
+ if response.status_code == 503:
40
+ raise EnvironmentNotReady("unknown", detail=detail)
41
+ if response.status_code == 410:
42
+ raise SessionExpired("unknown", detail=detail)
43
+ raise AppWorldAPIError(
44
+ detail or response.reason or "API error",
45
+ status_code=response.status_code,
46
+ detail=detail,
47
+ )
48
+
49
+
50
+ class _RemoteBaseEnv:
51
+ """Shared HTTP plumbing for remote environments."""
52
+
53
+ def __init__(
54
+ self,
55
+ api_key: str,
56
+ base_url: str,
57
+ env_id: str,
58
+ env_type: str,
59
+ timeout: float = 180.0,
60
+ ):
61
+ self.api_key = api_key
62
+ self.base_url = base_url.rstrip("/")
63
+ self.env_id = env_id
64
+ self.env_type = env_type
65
+ self.timeout = timeout
66
+ self.session_id: str | None = None
67
+ self.current_task: str | None = None
68
+
69
+ @property
70
+ def headers(self) -> dict[str, str]:
71
+ return {
72
+ "Authorization": f"Bearer {self.api_key}",
73
+ "Content-Type": "application/json",
74
+ }
75
+
76
+ def _post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
77
+ response = requests.post(
78
+ f"{self.base_url}{path}",
79
+ headers=self.headers,
80
+ json=payload,
81
+ timeout=self.timeout,
82
+ )
83
+ _raise_for_status(response)
84
+ return response.json()
85
+
86
+ def close(self) -> None:
87
+ if self.session_id is None:
88
+ return
89
+ try:
90
+ self._post("/api/v1/sdk/env/close", {"session_id": self.session_id})
91
+ except Exception:
92
+ pass
93
+ self.session_id = None
94
+ self.current_task = None
95
+
96
+
97
+ class RemoteAppWorldEnv(_RemoteBaseEnv):
98
+ """RL environment (5 discrete actions, screenshot observation)."""
99
+
100
+ def __init__(self, api_key: str, base_url: str, env_id: str):
101
+ super().__init__(api_key=api_key, base_url=base_url, env_id=env_id, env_type="rl")
102
+ self.observation_space = spaces.Box(low=0, high=255, shape=(320, 192, 3), dtype=np.uint8)
103
+ self.action_space = spaces.MultiDiscrete([5, 100, 100, 4])
104
+
105
+ def reset(
106
+ self,
107
+ *,
108
+ task_name: str,
109
+ seed: int | None = None,
110
+ options: dict | None = None,
111
+ ) -> tuple[np.ndarray, dict]:
112
+ # Close previous session if any
113
+ self.close()
114
+
115
+ payload = self._post("/api/v1/sdk/env/reset", {
116
+ "env_id": self.env_id,
117
+ "task_name": task_name,
118
+ "env_type": "rl",
119
+ })
120
+ self.session_id = payload["session_id"]
121
+ self.current_task = task_name
122
+ return _decode_data_url_png(payload["observation"]), payload["info"]
123
+
124
+ def step(self, action: np.ndarray) -> tuple[np.ndarray, float, bool, bool, dict]:
125
+ if self.session_id is None:
126
+ raise RuntimeError("reset() must be called before step()")
127
+ payload = self._post("/api/v1/sdk/env/step", {
128
+ "session_id": self.session_id,
129
+ "action": np.asarray(action).tolist(),
130
+ })
131
+ return (
132
+ _decode_data_url_png(payload["observation"]),
133
+ float(payload["reward"]),
134
+ bool(payload["terminated"]),
135
+ bool(payload["truncated"]),
136
+ payload["info"],
137
+ )
138
+
139
+
140
+ class RemoteAppWorldEvalEnv(_RemoteBaseEnv):
141
+ """Eval environment (7 actions incl. text input, dict observation)."""
142
+
143
+ def __init__(self, api_key: str, base_url: str, env_id: str):
144
+ super().__init__(api_key=api_key, base_url=base_url, env_id=env_id, env_type="eval")
145
+ self.observation_space = spaces.Dict({
146
+ "screenshot": spaces.Box(low=0, high=255, shape=(320, 192, 3), dtype=np.uint8),
147
+ "goal": spaces.Text(max_length=500),
148
+ })
149
+ self.action_space = spaces.Dict({
150
+ "action_type": spaces.Discrete(7),
151
+ "x": spaces.Box(0.0, 1.0, shape=(), dtype=np.float32),
152
+ "y": spaces.Box(0.0, 1.0, shape=(), dtype=np.float32),
153
+ "text": spaces.Text(max_length=200),
154
+ "direction": spaces.Discrete(4),
155
+ })
156
+
157
+ def reset(
158
+ self,
159
+ *,
160
+ task_name: str,
161
+ seed: int | None = None,
162
+ options: dict | None = None,
163
+ ) -> tuple[dict[str, Any], dict]:
164
+ # Close previous session if any
165
+ self.close()
166
+
167
+ payload = self._post("/api/v1/sdk/env/reset", {
168
+ "env_id": self.env_id,
169
+ "task_name": task_name,
170
+ "env_type": "eval",
171
+ })
172
+ self.session_id = payload["session_id"]
173
+ self.current_task = task_name
174
+ observation = payload["observation"]
175
+ return (
176
+ {"screenshot": _decode_data_url_png(observation["screenshot"]), "goal": observation["goal"]},
177
+ payload["info"],
178
+ )
179
+
180
+ def step(self, action: dict[str, Any]) -> tuple[dict[str, Any], float, bool, bool, dict]:
181
+ if self.session_id is None:
182
+ raise RuntimeError("reset() must be called before step()")
183
+ payload = self._post("/api/v1/sdk/env/step", {
184
+ "session_id": self.session_id,
185
+ "action": action,
186
+ })
187
+ observation = payload["observation"]
188
+ return (
189
+ {"screenshot": _decode_data_url_png(observation["screenshot"]), "goal": observation["goal"]},
190
+ float(payload["reward"]),
191
+ bool(payload["terminated"]),
192
+ bool(payload["truncated"]),
193
+ payload["info"],
194
+ )
appworld_sdk/errors.py ADDED
@@ -0,0 +1,38 @@
1
+ """App World SDK exception hierarchy."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class AppWorldError(Exception):
7
+ """Base exception for all App World SDK errors."""
8
+
9
+
10
+ class AppWorldAPIError(AppWorldError):
11
+ """Error returned by the App World API server."""
12
+
13
+ def __init__(self, message: str, *, status_code: int = 0, detail: str = ""):
14
+ self.status_code = status_code
15
+ self.detail = detail
16
+ super().__init__(f"[{status_code}] {message}" if status_code else message)
17
+
18
+
19
+ class EnvironmentNotReady(AppWorldAPIError):
20
+ """The requested environment is not available (no live backend)."""
21
+
22
+ def __init__(self, env_or_session_id: str, *, detail: str = ""):
23
+ super().__init__(
24
+ f"Environment or session '{env_or_session_id}' is not ready",
25
+ status_code=503,
26
+ detail=detail,
27
+ )
28
+
29
+
30
+ class SessionExpired(AppWorldAPIError):
31
+ """The SDK session has expired or been closed."""
32
+
33
+ def __init__(self, session_id: str, *, detail: str = ""):
34
+ super().__init__(
35
+ f"Session '{session_id}' has expired or been closed",
36
+ status_code=410,
37
+ detail=detail,
38
+ )
appworld_sdk/py.typed ADDED
File without changes
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: appworld-sdk
3
+ Version: 0.1.0
4
+ Summary: Client SDK for App World — RL & Eval environments for Android apps
5
+ Author: App World Contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/anthropics/app-world
8
+ Project-URL: Documentation, https://github.com/anthropics/app-world#readme
9
+ Project-URL: Repository, https://github.com/anthropics/app-world
10
+ Project-URL: Issues, https://github.com/anthropics/app-world/issues
11
+ Keywords: android,reinforcement-learning,gymnasium,evaluation,mobile
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: requests<3.0,>=2.28
22
+ Requires-Dist: numpy<3.0,>=1.24
23
+ Requires-Dist: Pillow<12.0,>=9.0
24
+ Requires-Dist: gymnasium<2.0,>=0.29
25
+ Dynamic: license-file
26
+
27
+ # App World SDK
28
+
29
+ Lightweight Python client for the **App World** platform — RL training and evaluation on real Android apps, with a standard [Gymnasium](https://gymnasium.farama.org/) interface.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install appworld-sdk
35
+ ```
36
+
37
+ **Requirements:** Python >= 3.11
38
+
39
+ ## Quick Start
40
+
41
+ ```python
42
+ from appworld_sdk import AppWorldClient
43
+
44
+ client = AppWorldClient(api_key="YOUR_API_KEY", base_url="https://api.appworld.dev")
45
+
46
+ # Browse available tasks
47
+ tasks = client.list_tasks()
48
+
49
+ # Allocate device resources
50
+ env_info = client.create_environment(task_ids=["FennoteCreateNote"])
51
+ env_id = env_info["id"]
52
+
53
+ # Get a Gymnasium-compatible environment
54
+ env = client.make_env(env_id=env_id, env_type="eval")
55
+
56
+ # Run a task
57
+ obs, info = env.reset(task_name="FennoteCreateNote")
58
+ done = False
59
+ while not done:
60
+ action = {"action_type": 0, "x": 0.5, "y": 0.5, "text": "", "direction": 0}
61
+ obs, reward, terminated, truncated, info = env.step(action)
62
+ done = terminated or truncated
63
+
64
+ env.close()
65
+ ```
66
+
67
+ ## Environment Types
68
+
69
+ | Type | Class | Actions | Use Case |
70
+ |------|-------|---------|----------|
71
+ | `"rl"` | `RemoteAppWorldEnv` | 5 discrete (tap, swipe, etc.) | RL training |
72
+ | `"eval"` | `RemoteAppWorldEvalEnv` | 7 (incl. text input) | Agent evaluation |
73
+
74
+ ## Client-Side Eval with Custom Agents
75
+
76
+ Implement the `BaseAgent` protocol to run evaluations where LLM calls stay on your side — your model API key never leaves the local process.
77
+
78
+ ```python
79
+ from appworld_sdk import AppWorldClient, BaseAgent
80
+
81
+ class MyAgent:
82
+ def predict(self, *, screenshot, goal, **kwargs) -> dict:
83
+ # Your model inference here
84
+ return {"action_type": 0, "x": 0.5, "y": 0.5, "text": "", "direction": 0}
85
+
86
+ client = AppWorldClient(api_key="YOUR_API_KEY")
87
+ env_info = client.create_environment(task_ids=["FennoteCreateNote", "FennoteDeleteNote"])
88
+
89
+ result = client.run_local_eval(
90
+ env_id=env_info["id"],
91
+ tasks=["FennoteCreateNote", "FennoteDeleteNote"],
92
+ agent=MyAgent(),
93
+ max_steps=15,
94
+ )
95
+
96
+ print(f"Success rate: {result.success_rate:.0%}")
97
+ print(f"Avg steps: {result.avg_steps:.1f}")
98
+ ```
99
+
100
+ ## Server-Side Eval
101
+
102
+ Let the platform handle LLM calls:
103
+
104
+ ```python
105
+ result = client.run_eval(
106
+ env_id=env_info["id"],
107
+ tasks=["FennoteCreateNote"],
108
+ model_provider="anthropic",
109
+ model_api_key="YOUR_MODEL_KEY",
110
+ model_name="claude-sonnet-4-20250514",
111
+ )
112
+ print(f"Success rate: {result.success_rate}")
113
+ ```
114
+
115
+ ## API Reference
116
+
117
+ ### `AppWorldClient(api_key, base_url, timeout)`
118
+
119
+ | Method | Description |
120
+ |--------|-------------|
121
+ | `list_apps(**filters)` | List available apps |
122
+ | `list_tasks(**filters)` | List available tasks |
123
+ | `get_task(task_id)` | Get task details |
124
+ | `create_environment(task_ids, name)` | Allocate device resources |
125
+ | `delete_environment(env_id)` | Release resources |
126
+ | `make_env(env_id, env_type)` | Create Gymnasium env |
127
+ | `run_eval(...)` | Server-side evaluation |
128
+ | `run_local_eval(...)` | Client-side evaluation |
129
+
130
+ ### Exceptions
131
+
132
+ | Exception | HTTP | Meaning |
133
+ |-----------|------|---------|
134
+ | `AppWorldError` | — | Base exception |
135
+ | `AppWorldAPIError` | any | Server returned an error |
136
+ | `EnvironmentNotReady` | 503 | Device not available |
137
+ | `SessionExpired` | 410 | Session closed or timed out |
138
+
139
+ ## License
140
+
141
+ Apache 2.0 — see [LICENSE](LICENSE) for details.
@@ -0,0 +1,11 @@
1
+ appworld_sdk/__init__.py,sha256=SrlajubHTsiAMMysvnZ8efdjTwE44PCZ7D9qM8apwec,821
2
+ appworld_sdk/agent.py,sha256=sVmZPKQWuCJYIqIDapsBjTj1PTxoQmNVQhhZ97CBV2M,1112
3
+ appworld_sdk/client.py,sha256=Cano9MPj6CR4RiyOAEynPvZJLJCioXqCjkEqTqfMbRY,17430
4
+ appworld_sdk/env.py,sha256=RaxIzK_IyI9T6s1xV1Ix5_Il-bbuHgawZopDF2alYdY,6468
5
+ appworld_sdk/errors.py,sha256=V2MK80-Vfcm2kOt73sRF_WcCdyeim9f5EmEY-Pf_Ruc,1166
6
+ appworld_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ appworld_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=GsyI097vvTujs35rsA9mDo_8Z13esTTJ8LLFSH6YHI0,10774
8
+ appworld_sdk-0.1.0.dist-info/METADATA,sha256=AUAPTCaX-7vIPmo3bKporUd35Bif-p0KNDcPieiYY1I,4394
9
+ appworld_sdk-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ appworld_sdk-0.1.0.dist-info/top_level.txt,sha256=z43Vxbs5luZ2oCEzCEZsY1f2MIfOwU6P8UYTf7asK8c,13
11
+ appworld_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 App World Contributors
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1 @@
1
+ appworld_sdk