earthdots 0.2.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.
- earthdots/__init__.py +1 -0
- earthdots/__main__.py +43 -0
- earthdots/app.py +341 -0
- earthdots/catalog.py +94 -0
- earthdots/config.py +197 -0
- earthdots/data/truth.json +1 -0
- earthdots/errors.py +9 -0
- earthdots/grid.py +31 -0
- earthdots/runner.py +242 -0
- earthdots/store.py +454 -0
- earthdots/web/assets/art/earth-art.css +57 -0
- earthdots/web/assets/art/earth-orbit.jpg +0 -0
- earthdots/web/assets/index-BxBtOJeG.js +14 -0
- earthdots/web/assets/index-fzJA3R-W.css +1 -0
- earthdots/web/assets/lexend-latin-ext-wght-normal-B6JQhE1e.woff2 +0 -0
- earthdots/web/assets/lexend-latin-wght-normal-ci0D1wrL.woff2 +0 -0
- earthdots/web/assets/lexend-vietnamese-wght-normal-RvljkFvg.woff2 +0 -0
- earthdots/web/favicon.svg +13 -0
- earthdots/web/index.html +15 -0
- earthdots-0.2.0.dist-info/METADATA +224 -0
- earthdots-0.2.0.dist-info/RECORD +25 -0
- earthdots-0.2.0.dist-info/WHEEL +4 -0
- earthdots-0.2.0.dist-info/entry_points.txt +2 -0
- earthdots-0.2.0.dist-info/licenses/LICENSE +21 -0
- earthdots-0.2.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +217 -0
earthdots/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Earthdots local evaluation workbench."""
|
earthdots/__main__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os
|
|
3
|
+
import threading
|
|
4
|
+
import webbrowser
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import uvicorn
|
|
8
|
+
|
|
9
|
+
from .config import Settings, version
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main():
|
|
13
|
+
parser = argparse.ArgumentParser(
|
|
14
|
+
prog="earthdots",
|
|
15
|
+
description="Ask a language model whether each point on Earth is land or water, and watch the map appear.")
|
|
16
|
+
parser.add_argument("--port", type=int, default=8765, help="local port (default: 8765)")
|
|
17
|
+
parser.add_argument("--data-dir", type=Path, metavar="PATH",
|
|
18
|
+
help="where runs and providers are stored (default: per-user data directory)")
|
|
19
|
+
parser.add_argument("--no-open", action="store_true", help="do not open the browser")
|
|
20
|
+
parser.add_argument("--reload", action="store_true", help="restart on source changes (development)")
|
|
21
|
+
parser.add_argument("--version", action="version", version=f"earthdots {version()}")
|
|
22
|
+
args = parser.parse_args()
|
|
23
|
+
if args.data_dir:
|
|
24
|
+
# The app factory runs in the server process (and again on reload), so it reads the environment.
|
|
25
|
+
# Set explicitly so a database named in a .env file cannot take precedence over the flag.
|
|
26
|
+
home = args.data_dir.expanduser().resolve()
|
|
27
|
+
os.environ["EARTHDOTS_HOME"] = str(home)
|
|
28
|
+
os.environ["EARTHDOTS_DATABASE"] = str(home / "earthdots.sqlite3")
|
|
29
|
+
settings = Settings.from_env()
|
|
30
|
+
url = f"http://127.0.0.1:{args.port}"
|
|
31
|
+
# Flushed so the address shows up at once when the output is piped or logged.
|
|
32
|
+
print(f"\n earthdots {version()}\n ➜ {url}\n data: {settings.database}\n", flush=True)
|
|
33
|
+
if not (settings.web_dir / "index.html").is_file():
|
|
34
|
+
print(" The web interface has not been built yet. Run: npm ci && npm run build\n", flush=True)
|
|
35
|
+
elif not args.no_open and not args.reload:
|
|
36
|
+
threading.Timer(1.0, webbrowser.open, args=(url,)).start()
|
|
37
|
+
# Bound to this machine only: the API can spend provider credits and has no authentication.
|
|
38
|
+
uvicorn.run("earthdots.app:create_app", factory=True, host="127.0.0.1", port=args.port,
|
|
39
|
+
reload=args.reload, timeout_graceful_shutdown=3, log_level="warning")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
main()
|
earthdots/app.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
from contextlib import asynccontextmanager
|
|
4
|
+
from typing import Any, Literal
|
|
5
|
+
from urllib.parse import urlsplit
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
from fastapi import FastAPI, Request
|
|
9
|
+
from fastapi.exceptions import RequestValidationError
|
|
10
|
+
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
|
11
|
+
from fastapi.staticfiles import StaticFiles
|
|
12
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
13
|
+
from starlette.middleware.gzip import GZipMiddleware
|
|
14
|
+
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
|
15
|
+
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
16
|
+
|
|
17
|
+
from .catalog import ModelCatalog
|
|
18
|
+
from .config import (
|
|
19
|
+
DEFAULT_AUTO_RETRIES,
|
|
20
|
+
DEFAULT_TEMPERATURE,
|
|
21
|
+
MAX_AUTO_RETRIES,
|
|
22
|
+
MAX_CONCURRENCY,
|
|
23
|
+
PRESETS,
|
|
24
|
+
PROMPT,
|
|
25
|
+
Settings,
|
|
26
|
+
validate_base_url,
|
|
27
|
+
validate_extra_body,
|
|
28
|
+
validate_key_env,
|
|
29
|
+
validate_model,
|
|
30
|
+
version,
|
|
31
|
+
)
|
|
32
|
+
from .errors import Problem
|
|
33
|
+
from .grid import STEPS, Grid
|
|
34
|
+
from .runner import Client, Runner
|
|
35
|
+
from .store import Store
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Strict(BaseModel):
|
|
39
|
+
model_config = ConfigDict(extra="forbid")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ProviderFields(Strict):
|
|
43
|
+
name: str | None = Field(default=None, min_length=1, max_length=60)
|
|
44
|
+
kind: Literal["openai", "systemone"] | None = None
|
|
45
|
+
base_url: str | None = None
|
|
46
|
+
# Omitted keeps the stored key; an empty string clears it.
|
|
47
|
+
api_key: str | None = Field(default=None, max_length=500)
|
|
48
|
+
key_env: str | None = None
|
|
49
|
+
extra_body: dict[str, Any] | None = None
|
|
50
|
+
|
|
51
|
+
@field_validator("base_url")
|
|
52
|
+
@classmethod
|
|
53
|
+
def valid_base_url(cls, value):
|
|
54
|
+
return value if value is None else validate_base_url(value)
|
|
55
|
+
|
|
56
|
+
@field_validator("key_env")
|
|
57
|
+
@classmethod
|
|
58
|
+
def valid_key_env(cls, value):
|
|
59
|
+
return value if value is None else validate_key_env(value)
|
|
60
|
+
|
|
61
|
+
@field_validator("extra_body")
|
|
62
|
+
@classmethod
|
|
63
|
+
def valid_extra_body(cls, value):
|
|
64
|
+
return value if value is None else validate_extra_body(value)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class NewProvider(ProviderFields):
|
|
68
|
+
name: str = Field(min_length=1, max_length=60)
|
|
69
|
+
kind: Literal["openai", "systemone"] = "openai"
|
|
70
|
+
base_url: str
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ModelChoice(Strict):
|
|
74
|
+
provider_id: str | None = None
|
|
75
|
+
model: str | None = None
|
|
76
|
+
temperature: float | None = Field(default=DEFAULT_TEMPERATURE, ge=0, le=2, strict=True)
|
|
77
|
+
# Omitted uses the provider's defaults; an explicit object replaces them for this run.
|
|
78
|
+
extra_body: dict[str, Any] | None = None
|
|
79
|
+
|
|
80
|
+
@field_validator("model")
|
|
81
|
+
@classmethod
|
|
82
|
+
def valid_model(cls, value):
|
|
83
|
+
return value if value is None else validate_model(value)
|
|
84
|
+
|
|
85
|
+
@field_validator("extra_body")
|
|
86
|
+
@classmethod
|
|
87
|
+
def valid_extra_body(cls, value):
|
|
88
|
+
return value if value is None else validate_extra_body(value)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class NewRun(ModelChoice):
|
|
92
|
+
mode: Literal["demo", "api"] = "demo"
|
|
93
|
+
step: Literal[1, 2, 5, 10] = 2
|
|
94
|
+
limit: int | None = Field(default=None, ge=1, strict=True)
|
|
95
|
+
concurrency: int = Field(default=1, ge=1, le=MAX_CONCURRENCY, strict=True)
|
|
96
|
+
auto_retries: int = Field(default=DEFAULT_AUTO_RETRIES, ge=0, le=MAX_AUTO_RETRIES, strict=True)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class LocalRequestsMiddleware:
|
|
100
|
+
"""Pure ASGI middleware keeps streaming cancellation and disconnect signals intact."""
|
|
101
|
+
|
|
102
|
+
def __init__(self, app: ASGIApp):
|
|
103
|
+
self.app = app
|
|
104
|
+
|
|
105
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send):
|
|
106
|
+
if scope["type"] != "http":
|
|
107
|
+
return await self.app(scope, receive, send)
|
|
108
|
+
headers = dict(scope.get("headers", []))
|
|
109
|
+
if scope["method"] in ("POST", "PUT", "DELETE", "PATCH"):
|
|
110
|
+
origin = headers.get(b"origin", b"").decode()
|
|
111
|
+
if origin and urlsplit(origin).netloc != headers.get(b"host", b"").decode():
|
|
112
|
+
problem = Problem("cross_site", "Cross-site request rejected", 403)
|
|
113
|
+
return await JSONResponse(problem.payload(), status_code=403)(scope, receive, send)
|
|
114
|
+
|
|
115
|
+
async def send_response(message: Message):
|
|
116
|
+
if message["type"] == "http.response.start" and scope["path"].startswith("/api/"):
|
|
117
|
+
message["headers"] = [(key, value) for key, value in message.get("headers", [])
|
|
118
|
+
if key.lower() != b"cache-control"] + [(b"cache-control", b"no-store")]
|
|
119
|
+
await send(message)
|
|
120
|
+
await self.app(scope, receive, send_response)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def create_app(settings: Settings | None = None, client: Client | None = None):
|
|
124
|
+
settings = settings or Settings.from_env()
|
|
125
|
+
|
|
126
|
+
@asynccontextmanager
|
|
127
|
+
async def lifespan(app: FastAPI):
|
|
128
|
+
store = Store(settings.database)
|
|
129
|
+
store.recover()
|
|
130
|
+
app.state.store = store
|
|
131
|
+
app.state.grid = Grid(settings.truth_path)
|
|
132
|
+
runner = Runner(store, client or Client(settings))
|
|
133
|
+
app.state.runner = runner
|
|
134
|
+
app.state.catalog = ModelCatalog(runner.client)
|
|
135
|
+
yield
|
|
136
|
+
await runner.close()
|
|
137
|
+
store.close()
|
|
138
|
+
|
|
139
|
+
app = FastAPI(title="Earthdots", version=version(), lifespan=lifespan, docs_url=None, redoc_url=None)
|
|
140
|
+
app.add_middleware(TrustedHostMiddleware, allowed_hosts=list(settings.allowed_hosts))
|
|
141
|
+
app.add_middleware(LocalRequestsMiddleware)
|
|
142
|
+
app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=3)
|
|
143
|
+
|
|
144
|
+
@app.exception_handler(Problem)
|
|
145
|
+
async def problem(request, error: Problem):
|
|
146
|
+
return JSONResponse(error.payload(), status_code=error.status)
|
|
147
|
+
|
|
148
|
+
@app.exception_handler(KeyError)
|
|
149
|
+
async def missing(request, error):
|
|
150
|
+
return JSONResponse(Problem("not_found", "Record not found", 404).payload(), status_code=404)
|
|
151
|
+
|
|
152
|
+
@app.exception_handler(ValueError)
|
|
153
|
+
async def rejected(request, error: ValueError):
|
|
154
|
+
return JSONResponse(Problem("invalid_request", str(error), 422).payload(), status_code=422)
|
|
155
|
+
|
|
156
|
+
@app.exception_handler(RequestValidationError)
|
|
157
|
+
async def invalid(request, error: RequestValidationError):
|
|
158
|
+
first = error.errors()[0] if error.errors() else {}
|
|
159
|
+
field = ".".join(str(part) for part in first.get("loc", ())[1:])
|
|
160
|
+
message = str(first.get("msg", "Invalid request")).removeprefix("Value error, ")
|
|
161
|
+
return JSONResponse(Problem("invalid_request", f"{field}: {message}" if field else message, 422,
|
|
162
|
+
field=field).payload(), status_code=422)
|
|
163
|
+
|
|
164
|
+
@app.get("/api/config")
|
|
165
|
+
async def config():
|
|
166
|
+
return {"version": version(), "prompt": PROMPT, "presets": PRESETS, "steps": list(STEPS),
|
|
167
|
+
"defaults": {"temperature": DEFAULT_TEMPERATURE, "auto_retries": DEFAULT_AUTO_RETRIES},
|
|
168
|
+
"max_concurrency": MAX_CONCURRENCY, "max_auto_retries": MAX_AUTO_RETRIES,
|
|
169
|
+
"live_point_limit": settings.live_point_limit,
|
|
170
|
+
"total_live_tokens": app.state.store.total_live_tokens()}
|
|
171
|
+
|
|
172
|
+
@app.get("/api/grid/{step}")
|
|
173
|
+
async def grid(step: int):
|
|
174
|
+
if step not in STEPS:
|
|
175
|
+
raise Problem("invalid_step", "Unsupported grid spacing", 400)
|
|
176
|
+
return app.state.grid.get(step)
|
|
177
|
+
|
|
178
|
+
@app.get("/api/providers")
|
|
179
|
+
async def providers():
|
|
180
|
+
return app.state.store.providers()
|
|
181
|
+
|
|
182
|
+
@app.post("/api/providers", status_code=201)
|
|
183
|
+
async def create_provider(body: NewProvider):
|
|
184
|
+
return app.state.store.save_provider(body.model_dump(exclude_unset=True) | {"kind": body.kind})
|
|
185
|
+
|
|
186
|
+
@app.patch("/api/providers/{provider_id}")
|
|
187
|
+
async def update_provider(provider_id: str, body: ProviderFields):
|
|
188
|
+
changes = body.model_dump(exclude_unset=True)
|
|
189
|
+
for field in ("name", "kind", "base_url"):
|
|
190
|
+
if field in changes and changes[field] is None:
|
|
191
|
+
raise ValueError(f"{field} cannot be null")
|
|
192
|
+
return app.state.store.save_provider(changes, provider_id)
|
|
193
|
+
|
|
194
|
+
@app.delete("/api/providers/{provider_id}")
|
|
195
|
+
async def delete_provider(provider_id: str):
|
|
196
|
+
app.state.store.delete_provider(provider_id)
|
|
197
|
+
return {"id": provider_id}
|
|
198
|
+
|
|
199
|
+
@app.get("/api/providers/{provider_id}/models")
|
|
200
|
+
async def models(provider_id: str, refresh: bool = False):
|
|
201
|
+
store = app.state.store
|
|
202
|
+
row = store.provider_row(provider_id)
|
|
203
|
+
key = store.endpoint({"provider": dict(row)})["key"]
|
|
204
|
+
try:
|
|
205
|
+
return await app.state.catalog.get(dict(row), key, refresh)
|
|
206
|
+
except httpx.HTTPError as error:
|
|
207
|
+
raise Problem("catalog_unreachable", "Could not reach the provider's model list", 502) from error
|
|
208
|
+
|
|
209
|
+
@app.get("/api/runs")
|
|
210
|
+
async def runs():
|
|
211
|
+
return app.state.store.list_runs()
|
|
212
|
+
|
|
213
|
+
def start_run(body: NewRun, purpose: str = "evaluation"):
|
|
214
|
+
if app.state.runner.busy:
|
|
215
|
+
raise Problem("busy", "Another run is in progress; pause it first")
|
|
216
|
+
total = (180 // body.step) * (360 // body.step)
|
|
217
|
+
if body.limit is not None and body.limit > total:
|
|
218
|
+
raise Problem("limit_exceeds_grid", f"This grid has only {total} points", 400, total=total)
|
|
219
|
+
if body.mode == "api":
|
|
220
|
+
if not body.provider_id:
|
|
221
|
+
raise Problem("provider_required", "Choose a provider first", 400)
|
|
222
|
+
if not body.model:
|
|
223
|
+
raise Problem("model_required", "Enter a model ID first", 400)
|
|
224
|
+
cap = settings.live_point_limit
|
|
225
|
+
if cap is not None and (body.limit or total) > cap:
|
|
226
|
+
raise Problem("live_limit", f"EARTHDOTS_LIVE_POINT_LIMIT allows at most {cap} real requests per run",
|
|
227
|
+
400, limit=cap)
|
|
228
|
+
run_id = app.state.store.create(
|
|
229
|
+
app.state.grid, body.mode, body.step, body.limit, body.concurrency, model=body.model,
|
|
230
|
+
provider=body.provider_id, purpose=purpose, auto_retries=body.auto_retries,
|
|
231
|
+
temperature=body.temperature, extra_body=body.extra_body)
|
|
232
|
+
try:
|
|
233
|
+
app.state.runner.start(run_id)
|
|
234
|
+
except Problem:
|
|
235
|
+
app.state.store.delete_run(run_id)
|
|
236
|
+
raise
|
|
237
|
+
return app.state.store.summary(run_id)
|
|
238
|
+
|
|
239
|
+
@app.post("/api/runs", status_code=201)
|
|
240
|
+
async def create(body: NewRun):
|
|
241
|
+
return start_run(body)
|
|
242
|
+
|
|
243
|
+
@app.post("/api/model-tests", status_code=201)
|
|
244
|
+
async def test_model(body: ModelChoice):
|
|
245
|
+
"""Send exactly one real request with the run's prompt and parameters."""
|
|
246
|
+
return start_run(NewRun(mode="api", step=2, limit=1, auto_retries=0, **body.model_dump()),
|
|
247
|
+
purpose="model_test")
|
|
248
|
+
|
|
249
|
+
@app.post("/api/runs/{run_id}/retry")
|
|
250
|
+
async def retry(run_id: str):
|
|
251
|
+
if app.state.runner.busy:
|
|
252
|
+
raise Problem("busy", "Another run is in progress; pause it first")
|
|
253
|
+
row = app.state.store.row(run_id)
|
|
254
|
+
if row["mode"] == "api":
|
|
255
|
+
app.state.store.endpoint(json.loads(row["config"]))
|
|
256
|
+
app.state.store.retry_failed(run_id)
|
|
257
|
+
app.state.runner.start(run_id, retry_only=True)
|
|
258
|
+
return app.state.store.summary(run_id)
|
|
259
|
+
|
|
260
|
+
@app.get("/api/runs/{run_id}/points/{idx}/attempts")
|
|
261
|
+
async def attempts(run_id: str, idx: int):
|
|
262
|
+
app.state.store.row(run_id)
|
|
263
|
+
return app.state.store.attempts_for_point(run_id, idx)
|
|
264
|
+
|
|
265
|
+
@app.get("/api/runs/{run_id}")
|
|
266
|
+
async def run(run_id: str):
|
|
267
|
+
return JSONResponse({"run": app.state.store.summary(run_id), "points": app.state.store.points(run_id)})
|
|
268
|
+
|
|
269
|
+
@app.post("/api/runs/{run_id}/pause")
|
|
270
|
+
async def pause(run_id: str):
|
|
271
|
+
app.state.runner.pause(run_id)
|
|
272
|
+
return app.state.store.summary(run_id)
|
|
273
|
+
|
|
274
|
+
@app.post("/api/runs/{run_id}/resume")
|
|
275
|
+
async def resume(run_id: str):
|
|
276
|
+
app.state.runner.start(run_id)
|
|
277
|
+
return app.state.store.summary(run_id)
|
|
278
|
+
|
|
279
|
+
@app.get("/api/requests/{request_id}")
|
|
280
|
+
async def get_request(request_id: int):
|
|
281
|
+
return app.state.store.request(request_id)
|
|
282
|
+
|
|
283
|
+
@app.delete("/api/runs/{run_id}")
|
|
284
|
+
async def delete_run(run_id: str):
|
|
285
|
+
app.state.store.delete_run(run_id)
|
|
286
|
+
return {"id": run_id}
|
|
287
|
+
|
|
288
|
+
@app.get("/api/runs/{run_id}/export")
|
|
289
|
+
async def export(run_id: str):
|
|
290
|
+
app.state.store.row(run_id)
|
|
291
|
+
return StreamingResponse(app.state.store.export(run_id), media_type="application/x-ndjson",
|
|
292
|
+
headers={"Content-Disposition": f'attachment; filename="earthdots-{run_id}.jsonl"'})
|
|
293
|
+
|
|
294
|
+
@app.get("/api/runs/{run_id}/events")
|
|
295
|
+
async def events(run_id: str, request: Request, since: int = 0):
|
|
296
|
+
app.state.store.row(run_id)
|
|
297
|
+
try:
|
|
298
|
+
cursor = max(0, since, int(request.headers.get("last-event-id", "0")))
|
|
299
|
+
except ValueError:
|
|
300
|
+
raise Problem("invalid_cursor", "Invalid event cursor", 400) from None
|
|
301
|
+
|
|
302
|
+
async def stream():
|
|
303
|
+
nonlocal cursor
|
|
304
|
+
ticks = 0
|
|
305
|
+
while True:
|
|
306
|
+
try:
|
|
307
|
+
row = app.state.store.row(run_id)
|
|
308
|
+
if row["revision"] > cursor:
|
|
309
|
+
snapshot = {"run": app.state.store.summary(run_id),
|
|
310
|
+
"points": app.state.store.points(run_id, cursor)}
|
|
311
|
+
cursor = snapshot["run"]["revision"]
|
|
312
|
+
yield f"id: {cursor}\ndata: {json.dumps(snapshot, ensure_ascii=False)}\n\n"
|
|
313
|
+
elif ticks % 50 == 0:
|
|
314
|
+
yield ": heartbeat\n\n"
|
|
315
|
+
if row["state"] in ('completed', 'needs_attention'):
|
|
316
|
+
return
|
|
317
|
+
except KeyError:
|
|
318
|
+
return
|
|
319
|
+
ticks += 1
|
|
320
|
+
await asyncio.sleep(0.15)
|
|
321
|
+
|
|
322
|
+
return StreamingResponse(stream(), media_type="text/event-stream",
|
|
323
|
+
headers={"X-Accel-Buffering": "no", "Cache-Control": "no-cache"})
|
|
324
|
+
|
|
325
|
+
if (settings.web_dir / "index.html").is_file():
|
|
326
|
+
app.mount("/assets", StaticFiles(directory=settings.web_dir / "assets"), name="assets")
|
|
327
|
+
|
|
328
|
+
@app.get("/favicon.svg")
|
|
329
|
+
async def favicon():
|
|
330
|
+
return FileResponse(settings.web_dir / "favicon.svg")
|
|
331
|
+
|
|
332
|
+
@app.get("/")
|
|
333
|
+
async def index():
|
|
334
|
+
return FileResponse(settings.web_dir / "index.html")
|
|
335
|
+
else:
|
|
336
|
+
@app.get("/")
|
|
337
|
+
async def unbuilt():
|
|
338
|
+
return JSONResponse(Problem(
|
|
339
|
+
"unbuilt", "The web interface has not been built. Run: npm ci && npm run build", 503,
|
|
340
|
+
).payload(), status_code=503)
|
|
341
|
+
return app
|
earthdots/catalog.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Model discovery through each provider's `/models` listing. Listing never sends an inference request."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import re
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from .config import validate_model
|
|
7
|
+
from .errors import Problem
|
|
8
|
+
|
|
9
|
+
# Listings mix chat models with image, audio and embedding services; drop what cannot answer in text.
|
|
10
|
+
NON_LANGUAGE = re.compile(
|
|
11
|
+
r"(?:image|audio|speech|tts|asr|realtime|livetranslate|s2s|omni|embed|rerank|ocr|video|whisper|dall-e"
|
|
12
|
+
r"|stable-diffusion|flux|wan\d|cosyvoice|fun-asr|qwen-mt|moderation|deep-research|deep-search|sre-gpu"
|
|
13
|
+
r"|imagen|veo|sora|lyria|guard)", re.IGNORECASE)
|
|
14
|
+
CACHE_SECONDS = 300
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def language_model(item: dict) -> bool:
|
|
18
|
+
name = item.get("id")
|
|
19
|
+
if not isinstance(name, str):
|
|
20
|
+
return False
|
|
21
|
+
try:
|
|
22
|
+
validate_model(name)
|
|
23
|
+
except ValueError:
|
|
24
|
+
return False
|
|
25
|
+
# Prefer declared capabilities; fall back to the name when a service lists IDs only.
|
|
26
|
+
architecture = item.get("architecture") if isinstance(item.get("architecture"), dict) else {}
|
|
27
|
+
output = item.get("output_modalities", architecture.get("output_modalities"))
|
|
28
|
+
if isinstance(output, list):
|
|
29
|
+
return bool(output) and all(modality == "text" for modality in output)
|
|
30
|
+
return not NON_LANGUAGE.search(name)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def systemone_model(item: dict) -> bool:
|
|
34
|
+
"""Gateways that proxy several APIs tag the System One family through its endpoint types."""
|
|
35
|
+
name = item.get("id")
|
|
36
|
+
if not isinstance(name, str):
|
|
37
|
+
return False
|
|
38
|
+
try:
|
|
39
|
+
validate_model(name)
|
|
40
|
+
except ValueError:
|
|
41
|
+
return False
|
|
42
|
+
endpoints = item.get("supported_endpoint_types")
|
|
43
|
+
return not isinstance(endpoints, list) or "typesafe-systemone" in endpoints
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ModelCatalog:
|
|
47
|
+
def __init__(self, client):
|
|
48
|
+
self.client = client
|
|
49
|
+
self.cache: dict[tuple, tuple[float, dict]] = {}
|
|
50
|
+
self.lock = asyncio.Lock()
|
|
51
|
+
|
|
52
|
+
async def get(self, provider: dict, key: str, refresh: bool = False) -> dict:
|
|
53
|
+
"""List one provider's models, cached per endpoint for five minutes."""
|
|
54
|
+
async with self.lock:
|
|
55
|
+
slot = (provider["id"], provider["base_url"], key)
|
|
56
|
+
cached = self.cache.get(slot)
|
|
57
|
+
if cached and not refresh and time.monotonic() - cached[0] < CACHE_SECONDS:
|
|
58
|
+
return cached[1]
|
|
59
|
+
classify = systemone_model if provider["kind"] == "systemone" else language_model
|
|
60
|
+
models = await self.collect(provider["base_url"], key, classify)
|
|
61
|
+
result = {"provider_id": provider["id"],
|
|
62
|
+
"models": sorted(models, key=lambda item: item["id"].lower())}
|
|
63
|
+
self.cache = {k: v for k, v in self.cache.items() if k[0] != provider["id"]}
|
|
64
|
+
self.cache[slot] = (time.monotonic(), result)
|
|
65
|
+
return result
|
|
66
|
+
|
|
67
|
+
async def collect(self, base_url: str, key: str, classify) -> list[dict]:
|
|
68
|
+
items, after, seen = [], None, set()
|
|
69
|
+
headers = {"Authorization": "Bearer " + key} if key else {}
|
|
70
|
+
for _ in range(20):
|
|
71
|
+
# The same cursor under both names: OpenAI-style listings read `after`, Anthropic's `after_id`.
|
|
72
|
+
response = await self.client.http.get(base_url + "/models", headers=headers,
|
|
73
|
+
params={"after": after, "after_id": after} if after else None)
|
|
74
|
+
if response.status_code != 200:
|
|
75
|
+
raise Problem("catalog_failed", f"Model list unavailable · HTTP {response.status_code}", 502,
|
|
76
|
+
http_status=response.status_code)
|
|
77
|
+
try:
|
|
78
|
+
data = response.json()
|
|
79
|
+
except ValueError:
|
|
80
|
+
data = None
|
|
81
|
+
page = data.get("data") if isinstance(data, dict) else None
|
|
82
|
+
if not isinstance(page, list):
|
|
83
|
+
raise Problem("catalog_malformed", "Model list has an unexpected format", 502)
|
|
84
|
+
for item in page:
|
|
85
|
+
if isinstance(item, dict) and classify(item) and item["id"] not in seen:
|
|
86
|
+
seen.add(item["id"])
|
|
87
|
+
items.append({"id": item["id"]})
|
|
88
|
+
if not data.get("has_more"):
|
|
89
|
+
return items
|
|
90
|
+
cursor = data.get("last_id")
|
|
91
|
+
if not isinstance(cursor, str) or cursor == after:
|
|
92
|
+
raise Problem("catalog_malformed", "Model list has an unexpected format", 502)
|
|
93
|
+
after = cursor
|
|
94
|
+
raise Problem("catalog_malformed", "Model list has an unexpected format", 502)
|
earthdots/config.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import sys
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from importlib import metadata
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from urllib.parse import urlsplit
|
|
9
|
+
|
|
10
|
+
from dotenv import load_dotenv
|
|
11
|
+
|
|
12
|
+
PACKAGE = Path(__file__).resolve().parent
|
|
13
|
+
TRUTH_PATH = PACKAGE / "data" / "truth.json"
|
|
14
|
+
MAX_CONCURRENCY = 100
|
|
15
|
+
MAX_AUTO_RETRIES = 3
|
|
16
|
+
DEFAULT_TEMPERATURE = 1.0
|
|
17
|
+
DEFAULT_AUTO_RETRIES = 2
|
|
18
|
+
PROMPT = (
|
|
19
|
+
"If this location is over land, say 'Land'. "
|
|
20
|
+
"If this location is over water, say 'Water'. "
|
|
21
|
+
"Do not say anything else. {coordinate}"
|
|
22
|
+
)
|
|
23
|
+
# Frozen systemone wording; the question ID stays a client-side key.
|
|
24
|
+
SYSTEMONE_STATE = "A location on Earth's surface: {coordinate}"
|
|
25
|
+
SYSTEMONE_INSTRUCTIONS = "Is this location over land or over water?"
|
|
26
|
+
SYSTEMONE_CRITERIA = {
|
|
27
|
+
"Land": "The point is over a continent, island, or other land surface, including inland terrain",
|
|
28
|
+
"Water": "The point is over an ocean, sea, lake, or other body of water",
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
# openai: POST {base_url}/chat/completions · systemone: POST {base_url}/systemone
|
|
32
|
+
KINDS = ("openai", "systemone")
|
|
33
|
+
# Keys the workbench owns; extra request parameters may not replace them.
|
|
34
|
+
RESERVED_BODY_KEYS = ("model", "messages", "temperature", "stream", "n")
|
|
35
|
+
DEMO_PROVIDER = {"id": "demo", "name": "Simulation", "kind": "demo", "base_url": ""}
|
|
36
|
+
|
|
37
|
+
# Starting points for the "add provider" form. Nothing here is contacted until a provider is saved.
|
|
38
|
+
PRESETS = [
|
|
39
|
+
{"id": "openai", "name": "OpenAI", "kind": "openai",
|
|
40
|
+
"base_url": "https://api.openai.com/v1", "key_env": "OPENAI_API_KEY", "extra_body": {}},
|
|
41
|
+
{"id": "anthropic", "name": "Anthropic", "kind": "openai",
|
|
42
|
+
"base_url": "https://api.anthropic.com/v1", "key_env": "ANTHROPIC_API_KEY", "extra_body": {}},
|
|
43
|
+
{"id": "gemini", "name": "Google Gemini", "kind": "openai",
|
|
44
|
+
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
45
|
+
"key_env": "GEMINI_API_KEY", "extra_body": {}},
|
|
46
|
+
{"id": "openrouter", "name": "OpenRouter", "kind": "openai",
|
|
47
|
+
"base_url": "https://openrouter.ai/api/v1", "key_env": "OPENROUTER_API_KEY", "extra_body": {}},
|
|
48
|
+
{"id": "deepseek", "name": "DeepSeek", "kind": "openai",
|
|
49
|
+
"base_url": "https://api.deepseek.com/v1", "key_env": "DEEPSEEK_API_KEY", "extra_body": {}},
|
|
50
|
+
{"id": "dashscope", "name": "Alibaba Bailian", "kind": "openai",
|
|
51
|
+
"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
|
52
|
+
"key_env": "DASHSCOPE_API_KEY", "extra_body": {"enable_thinking": False}},
|
|
53
|
+
{"id": "groq", "name": "Groq", "kind": "openai",
|
|
54
|
+
"base_url": "https://api.groq.com/openai/v1", "key_env": "GROQ_API_KEY", "extra_body": {}},
|
|
55
|
+
{"id": "mistral", "name": "Mistral", "kind": "openai",
|
|
56
|
+
"base_url": "https://api.mistral.ai/v1", "key_env": "MISTRAL_API_KEY", "extra_body": {}},
|
|
57
|
+
{"id": "xai", "name": "xAI", "kind": "openai",
|
|
58
|
+
"base_url": "https://api.x.ai/v1", "key_env": "XAI_API_KEY", "extra_body": {}},
|
|
59
|
+
{"id": "ollama", "name": "Ollama", "kind": "openai",
|
|
60
|
+
"base_url": "http://localhost:11434/v1", "key_env": "", "extra_body": {}},
|
|
61
|
+
{"id": "lmstudio", "name": "LM Studio", "kind": "openai",
|
|
62
|
+
"base_url": "http://localhost:1234/v1", "key_env": "", "extra_body": {}},
|
|
63
|
+
{"id": "systemone", "name": "TypeSafe System One", "kind": "systemone",
|
|
64
|
+
"base_url": "", "key_env": "TYPESAFE_API_KEY", "extra_body": {}},
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def version() -> str:
|
|
69
|
+
try:
|
|
70
|
+
return metadata.version("earthdots")
|
|
71
|
+
except metadata.PackageNotFoundError:
|
|
72
|
+
return "0.0.0"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def default_home() -> Path:
|
|
76
|
+
"""Per-user data directory, following each platform's convention."""
|
|
77
|
+
if sys.platform == "win32":
|
|
78
|
+
base = os.getenv("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
|
|
79
|
+
elif sys.platform == "darwin":
|
|
80
|
+
base = str(Path.home() / "Library" / "Application Support")
|
|
81
|
+
else:
|
|
82
|
+
base = os.getenv("XDG_DATA_HOME") or str(Path.home() / ".local" / "share")
|
|
83
|
+
return Path(base) / "earthdots"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def resolve_database() -> Path:
|
|
87
|
+
if os.getenv("EARTHDOTS_DATABASE"):
|
|
88
|
+
return Path(os.environ["EARTHDOTS_DATABASE"]).expanduser()
|
|
89
|
+
if os.getenv("EARTHDOTS_HOME"):
|
|
90
|
+
return Path(os.environ["EARTHDOTS_HOME"]).expanduser() / "earthdots.sqlite3"
|
|
91
|
+
# Checkouts from before the per-user data directory kept their history next to the code.
|
|
92
|
+
legacy = Path.cwd() / "runs" / "earthdots.sqlite3"
|
|
93
|
+
return legacy if legacy.is_file() else default_home() / "earthdots.sqlite3"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass
|
|
97
|
+
class Settings:
|
|
98
|
+
database: Path = field(default_factory=lambda: default_home() / "earthdots.sqlite3")
|
|
99
|
+
truth_path: Path = TRUTH_PATH
|
|
100
|
+
web_dir: Path = PACKAGE / "web"
|
|
101
|
+
# Optional safety cap on real requests per run; None leaves the grid size as the only limit.
|
|
102
|
+
live_point_limit: int | None = None
|
|
103
|
+
# Host headers the server answers to. Loopback names only, so a rebound DNS name is refused.
|
|
104
|
+
allowed_hosts: tuple[str, ...] = ("localhost", "127.0.0.1", "[::1]")
|
|
105
|
+
demo_delay: float = 0.006
|
|
106
|
+
retry_delay: float = 1.0
|
|
107
|
+
|
|
108
|
+
@classmethod
|
|
109
|
+
def from_env(cls):
|
|
110
|
+
load_dotenv(Path.cwd() / ".env", override=False)
|
|
111
|
+
database = resolve_database()
|
|
112
|
+
load_dotenv(database.parent / ".env", override=False)
|
|
113
|
+
limit = os.getenv("EARTHDOTS_LIVE_POINT_LIMIT", "").strip()
|
|
114
|
+
settings = cls(database=database, live_point_limit=int(limit) if limit else None)
|
|
115
|
+
if settings.live_point_limit is not None and settings.live_point_limit < 1:
|
|
116
|
+
raise ValueError("EARTHDOTS_LIVE_POINT_LIMIT must be positive")
|
|
117
|
+
return settings
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def coordinate(lat: float, lon: float) -> str:
|
|
121
|
+
return f"{abs(lat):g}° {'N' if lat >= 0 else 'S'}, {abs(lon):g}° {'E' if lon >= 0 else 'W'}"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def validate_model(value: str) -> str:
|
|
125
|
+
value = value.strip()
|
|
126
|
+
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,199}", value):
|
|
127
|
+
raise ValueError("Model ID must be 1-200 letters, digits or . _ : / @ + -")
|
|
128
|
+
return value
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def validate_kind(value: str) -> str:
|
|
132
|
+
if value not in KINDS:
|
|
133
|
+
raise ValueError("Provider type must be openai or systemone")
|
|
134
|
+
return value
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def validate_base_url(value: str) -> str:
|
|
138
|
+
value = value.strip().rstrip("/")
|
|
139
|
+
try:
|
|
140
|
+
url = urlsplit(value)
|
|
141
|
+
port = url.port
|
|
142
|
+
except ValueError as error:
|
|
143
|
+
raise ValueError("Invalid base URL") from error
|
|
144
|
+
if (url.scheme not in ("http", "https") or not url.hostname or url.username or url.password
|
|
145
|
+
or url.query or url.fragment or any(c.isspace() for c in value) or port == 0):
|
|
146
|
+
raise ValueError("Base URL must be an HTTP(S) address without credentials or query parameters")
|
|
147
|
+
return value
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def validate_key_env(value: str) -> str:
|
|
151
|
+
value = value.strip()
|
|
152
|
+
if value and not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,99}", value):
|
|
153
|
+
raise ValueError("Environment variable names use letters, digits and underscores")
|
|
154
|
+
return value
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def validate_extra_body(value) -> dict:
|
|
158
|
+
"""Extra request parameters are merged into every request body of a run."""
|
|
159
|
+
if value is None:
|
|
160
|
+
return {}
|
|
161
|
+
if not isinstance(value, dict):
|
|
162
|
+
raise ValueError("Extra parameters must be a JSON object") # noqa: TRY004 - reported as a 422
|
|
163
|
+
reserved = [key for key in value if key in RESERVED_BODY_KEYS]
|
|
164
|
+
if reserved:
|
|
165
|
+
raise ValueError(f"Extra parameters cannot set {', '.join(reserved)}")
|
|
166
|
+
if len(json.dumps(value, ensure_ascii=False)) > 4096:
|
|
167
|
+
raise ValueError("Extra parameters are limited to 4 KB")
|
|
168
|
+
return value
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def validate_temperature(value) -> float | None:
|
|
172
|
+
"""None omits the parameter, for models that reject or fix their sampling temperature."""
|
|
173
|
+
if value is None:
|
|
174
|
+
return None
|
|
175
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0 <= value <= 2:
|
|
176
|
+
raise ValueError("Temperature must be between 0 and 2")
|
|
177
|
+
return float(value)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def request_body(lat: float, lon: float, config: dict) -> dict:
|
|
181
|
+
"""Build the single request for one coordinate from a run's saved configuration."""
|
|
182
|
+
where = coordinate(lat, lon)
|
|
183
|
+
if config["provider"]["kind"] == "systemone":
|
|
184
|
+
return {
|
|
185
|
+
"model": config["model"],
|
|
186
|
+
"state": SYSTEMONE_STATE.format(coordinate=where),
|
|
187
|
+
"questions": {"terrain": {"type": "choice",
|
|
188
|
+
"instructions": SYSTEMONE_INSTRUCTIONS,
|
|
189
|
+
"criteria": SYSTEMONE_CRITERIA}},
|
|
190
|
+
}
|
|
191
|
+
params = config.get("params") or {}
|
|
192
|
+
body = {"model": config["model"],
|
|
193
|
+
"messages": [{"role": "user", "content": PROMPT.format(coordinate=where)}]}
|
|
194
|
+
if params.get("temperature") is not None:
|
|
195
|
+
body["temperature"] = params["temperature"]
|
|
196
|
+
body.update(params.get("extra_body") or {})
|
|
197
|
+
return body
|