margin-api 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.
- margin_api/__init__.py +3 -0
- margin_api/app.py +338 -0
- margin_api/jobs.py +253 -0
- margin_api/llm_settings.py +173 -0
- margin_api/main.py +17 -0
- margin_api/py.typed +1 -0
- margin_api/settings.py +32 -0
- margin_api/ui/assets/index-DIeVYF0g.js +11 -0
- margin_api/ui/assets/index-Do_ARaDC.css +1 -0
- margin_api/ui/fonts/OFL-fraunces.txt +93 -0
- margin_api/ui/fonts/OFL-instrument-sans.txt +93 -0
- margin_api/ui/fonts/OFL-jetbrains-mono.txt +93 -0
- margin_api/ui/fonts/fraunces-latin-ext.woff2 +0 -0
- margin_api/ui/fonts/fraunces-latin.woff2 +0 -0
- margin_api/ui/fonts/instrument-sans-latin-ext.woff2 +0 -0
- margin_api/ui/fonts/instrument-sans-latin.woff2 +0 -0
- margin_api/ui/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
- margin_api/ui/fonts/jetbrains-mono-latin.woff2 +0 -0
- margin_api/ui/index.html +22 -0
- margin_api/ui/mark.svg +1 -0
- margin_api-0.1.0.dist-info/METADATA +121 -0
- margin_api-0.1.0.dist-info/RECORD +25 -0
- margin_api-0.1.0.dist-info/WHEEL +4 -0
- margin_api-0.1.0.dist-info/entry_points.txt +2 -0
- margin_api-0.1.0.dist-info/licenses/LICENSE +21 -0
margin_api/__init__.py
ADDED
margin_api/app.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""The FastAPI application: list agents, start runs, follow them live, cancel them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, MutableMapping
|
|
7
|
+
from contextlib import asynccontextmanager
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
from fastapi import FastAPI, HTTPException, Query, Request
|
|
13
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
14
|
+
from fastapi.middleware.trustedhost import TrustedHostMiddleware
|
|
15
|
+
from fastapi.responses import FileResponse, JSONResponse
|
|
16
|
+
from fastapi.staticfiles import StaticFiles
|
|
17
|
+
from margin_core import (
|
|
18
|
+
AgentInfo,
|
|
19
|
+
AgentLoadError,
|
|
20
|
+
AgentNotFoundError,
|
|
21
|
+
AgentRegistry,
|
|
22
|
+
AgentResult,
|
|
23
|
+
BaseAgent,
|
|
24
|
+
InputValidationError,
|
|
25
|
+
ProgressEvent,
|
|
26
|
+
default_registry,
|
|
27
|
+
)
|
|
28
|
+
from margin_core.config import get_settings
|
|
29
|
+
from margin_core.llm import LLMClient, create_llm
|
|
30
|
+
from margin_core.logging import get_logger
|
|
31
|
+
from pydantic import BaseModel, Field
|
|
32
|
+
from sse_starlette.sse import EventSourceResponse
|
|
33
|
+
|
|
34
|
+
from margin_api import __version__
|
|
35
|
+
from margin_api.jobs import Run, RunManager, RunStatus
|
|
36
|
+
from margin_api.llm_settings import router as llm_settings_router
|
|
37
|
+
from margin_api.settings import ApiSettings, load_settings
|
|
38
|
+
|
|
39
|
+
logger = get_logger(__name__)
|
|
40
|
+
|
|
41
|
+
Scope = MutableMapping[str, Any]
|
|
42
|
+
Message = MutableMapping[str, Any]
|
|
43
|
+
Receive = Callable[[], Awaitable[Message]]
|
|
44
|
+
Send = Callable[[Message], Awaitable[None]]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class AgentList(BaseModel):
|
|
48
|
+
agents: list[AgentInfo]
|
|
49
|
+
load_errors: dict[str, str] = Field(
|
|
50
|
+
default_factory=dict, description="Installed agents that failed to load, and why."
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class RunCreated(BaseModel):
|
|
55
|
+
run_id: str
|
|
56
|
+
status: RunStatus
|
|
57
|
+
queue_position: int | None
|
|
58
|
+
links: dict[str, str]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class RunModel(BaseModel):
|
|
62
|
+
provider: str
|
|
63
|
+
model: str | None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class RunView(BaseModel):
|
|
67
|
+
run_id: str
|
|
68
|
+
agent_id: str
|
|
69
|
+
status: RunStatus
|
|
70
|
+
queue_position: int | None = Field(description="1 = next to start; null unless queued.")
|
|
71
|
+
progress: ProgressEvent | None
|
|
72
|
+
created_at: datetime
|
|
73
|
+
started_at: datetime | None
|
|
74
|
+
finished_at: datetime | None
|
|
75
|
+
result: AgentResult | None = Field(description="Present once the run is done.")
|
|
76
|
+
llm: RunModel | None = Field(default=None, description="The model this run uses, if any.")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class _BodyLimit:
|
|
80
|
+
"""Reject request bodies over ``limit`` bytes with 413, including chunked uploads.
|
|
81
|
+
|
|
82
|
+
The body is read here (it is small by definition) and replayed to the app, because an
|
|
83
|
+
error raised while the app reads its body would be reported as a generic 400.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(self, app: Any, limit: int) -> None:
|
|
87
|
+
self.app = app
|
|
88
|
+
self.limit = limit
|
|
89
|
+
|
|
90
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
91
|
+
if scope["type"] != "http" or scope.get("method") in {"GET", "HEAD", "DELETE", "OPTIONS"}:
|
|
92
|
+
await self.app(scope, receive, send)
|
|
93
|
+
return
|
|
94
|
+
headers = dict(scope.get("headers") or [])
|
|
95
|
+
declared = headers.get(b"content-length")
|
|
96
|
+
if declared is not None and declared.isdigit() and int(declared) > self.limit:
|
|
97
|
+
await self._reject(send)
|
|
98
|
+
return
|
|
99
|
+
chunks: list[bytes] = []
|
|
100
|
+
size = 0
|
|
101
|
+
while True:
|
|
102
|
+
message = await receive()
|
|
103
|
+
if message["type"] != "http.request":
|
|
104
|
+
break
|
|
105
|
+
chunk = message.get("body", b"")
|
|
106
|
+
size += len(chunk)
|
|
107
|
+
if size > self.limit:
|
|
108
|
+
await self._reject(send)
|
|
109
|
+
return
|
|
110
|
+
chunks.append(chunk)
|
|
111
|
+
if not message.get("more_body", False):
|
|
112
|
+
break
|
|
113
|
+
replayed = False
|
|
114
|
+
|
|
115
|
+
async def replay() -> Message:
|
|
116
|
+
nonlocal replayed
|
|
117
|
+
if not replayed:
|
|
118
|
+
replayed = True
|
|
119
|
+
return {"type": "http.request", "body": b"".join(chunks), "more_body": False}
|
|
120
|
+
return await receive()
|
|
121
|
+
|
|
122
|
+
await self.app(scope, replay, send)
|
|
123
|
+
|
|
124
|
+
async def _reject(self, send: Send) -> None:
|
|
125
|
+
body = json.dumps({"detail": f"Request body exceeds {self.limit} bytes"}).encode()
|
|
126
|
+
await send({"type": "http.response.start", "status": 413,
|
|
127
|
+
"headers": [(b"content-type", b"application/json")]}) # fmt: skip
|
|
128
|
+
await send({"type": "http.response.body", "body": body})
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
LLMFactory = Callable[[str | None, str | None], LLMClient | None]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _default_llm(provider: str | None, model: str | None) -> LLMClient | None:
|
|
135
|
+
"""A client built from the settings as they are now, so changes apply to the next run."""
|
|
136
|
+
return create_llm(provider, model)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def create_app(
|
|
140
|
+
*,
|
|
141
|
+
registry: AgentRegistry | None = None,
|
|
142
|
+
settings: ApiSettings | None = None,
|
|
143
|
+
llm_factory: LLMFactory | None = _default_llm,
|
|
144
|
+
) -> FastAPI:
|
|
145
|
+
settings = settings or load_settings()
|
|
146
|
+
registry = registry or default_registry()
|
|
147
|
+
manager = RunManager(registry, settings)
|
|
148
|
+
|
|
149
|
+
@asynccontextmanager
|
|
150
|
+
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
|
151
|
+
await manager.start()
|
|
152
|
+
try:
|
|
153
|
+
yield
|
|
154
|
+
finally:
|
|
155
|
+
await manager.stop()
|
|
156
|
+
|
|
157
|
+
app = FastAPI(
|
|
158
|
+
title="margin API",
|
|
159
|
+
version=__version__,
|
|
160
|
+
description=(
|
|
161
|
+
"Run any installed margin agent over HTTP. Runs are asynchronous: start one, "
|
|
162
|
+
"then poll it or follow its events (server-sent events) until the result arrives."
|
|
163
|
+
),
|
|
164
|
+
lifespan=lifespan,
|
|
165
|
+
)
|
|
166
|
+
app.state.manager = manager
|
|
167
|
+
app.add_middleware(
|
|
168
|
+
CORSMiddleware,
|
|
169
|
+
allow_origins=settings.cors_origins,
|
|
170
|
+
allow_methods=["GET", "POST", "PUT", "DELETE"],
|
|
171
|
+
allow_headers=["Content-Type", "Last-Event-ID"],
|
|
172
|
+
)
|
|
173
|
+
app.add_middleware(_BodyLimit, limit=settings.max_body_bytes)
|
|
174
|
+
ui_dir = Path(settings.ui_dir) if settings.ui_dir else _bundled_ui()
|
|
175
|
+
ui_root = _ui_root(ui_dir) if ui_dir is not None else None
|
|
176
|
+
if ui_root is not None:
|
|
177
|
+
app.add_middleware(_UIPages, root=ui_root)
|
|
178
|
+
# Only answer requests addressed to this machine by name. Without this, a web page could
|
|
179
|
+
# use DNS rebinding to reach the API through a domain of its own and read local results.
|
|
180
|
+
app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.allowed_hosts)
|
|
181
|
+
app.include_router(llm_settings_router)
|
|
182
|
+
|
|
183
|
+
def agent_class(agent_id: str) -> type[BaseAgent]:
|
|
184
|
+
try:
|
|
185
|
+
return registry.get_agent_class(agent_id)
|
|
186
|
+
except AgentNotFoundError as exc:
|
|
187
|
+
raise HTTPException(404, str(exc)) from exc
|
|
188
|
+
except AgentLoadError as exc:
|
|
189
|
+
raise HTTPException(500, f"Agent {agent_id!r} failed to load: {exc}") from exc
|
|
190
|
+
|
|
191
|
+
def find_run(run_id: str) -> Run:
|
|
192
|
+
run = manager.get(run_id)
|
|
193
|
+
if run is None:
|
|
194
|
+
raise HTTPException(404, f"No run {run_id!r} (unknown, or expired)")
|
|
195
|
+
return run
|
|
196
|
+
|
|
197
|
+
def view(run: Run) -> RunView:
|
|
198
|
+
llm = RunModel(provider=run.llm_provider, model=run.llm_model) if run.llm_provider else None
|
|
199
|
+
return RunView(
|
|
200
|
+
run_id=run.id, agent_id=run.agent_id, status=run.status,
|
|
201
|
+
queue_position=manager.queue_position(run), progress=run.progress,
|
|
202
|
+
created_at=run.created_at, started_at=run.started_at,
|
|
203
|
+
finished_at=run.finished_at, result=run.result,
|
|
204
|
+
llm=llm,
|
|
205
|
+
) # fmt: skip
|
|
206
|
+
|
|
207
|
+
@app.get("/health", tags=["meta"])
|
|
208
|
+
def health() -> dict[str, str]:
|
|
209
|
+
return {"status": "ok", "version": __version__}
|
|
210
|
+
|
|
211
|
+
@app.get("/agents", response_model=AgentList, tags=["agents"])
|
|
212
|
+
def list_agents() -> AgentList:
|
|
213
|
+
return AgentList(agents=registry.list_agents(), load_errors=registry.load_errors)
|
|
214
|
+
|
|
215
|
+
@app.get("/agents/{agent_id}", response_model=AgentInfo, tags=["agents"])
|
|
216
|
+
def get_agent(agent_id: str) -> AgentInfo:
|
|
217
|
+
return agent_class(agent_id).info()
|
|
218
|
+
|
|
219
|
+
@app.post(
|
|
220
|
+
"/agents/{agent_id}/runs",
|
|
221
|
+
status_code=202,
|
|
222
|
+
response_model=RunCreated,
|
|
223
|
+
tags=["runs"],
|
|
224
|
+
responses={422: {"description": "The input does not match the agent's input schema"}},
|
|
225
|
+
)
|
|
226
|
+
async def start_run(
|
|
227
|
+
agent_id: str,
|
|
228
|
+
body: dict[str, Any],
|
|
229
|
+
provider: Literal["local", "anthropic", "openai", "mock"] | None = Query(
|
|
230
|
+
default=None, description="Model provider for this run (default: from settings)."
|
|
231
|
+
),
|
|
232
|
+
model: str | None = Query(
|
|
233
|
+
default=None,
|
|
234
|
+
description="Model for this run (default: the provider's model in settings).",
|
|
235
|
+
),
|
|
236
|
+
) -> RunCreated:
|
|
237
|
+
cls = agent_class(agent_id)
|
|
238
|
+
try:
|
|
239
|
+
parsed = cls.parse_input(body)
|
|
240
|
+
except InputValidationError as exc:
|
|
241
|
+
raise HTTPException(422, str(exc)) from exc
|
|
242
|
+
llm: LLMClient | None = None
|
|
243
|
+
resolved = (provider or get_settings().default_llm_provider).lower()
|
|
244
|
+
if cls.uses_llm and llm_factory is not None:
|
|
245
|
+
try:
|
|
246
|
+
llm = llm_factory(provider, model)
|
|
247
|
+
except Exception as exc: # noqa: BLE001 - e.g. a missing API key
|
|
248
|
+
if provider or model: # a choice made for this run must work, or say why
|
|
249
|
+
raise HTTPException(422, f"Cannot use that model: {exc}") from exc
|
|
250
|
+
logger.warning("No model client for %s: %s", agent_id, exc)
|
|
251
|
+
run = manager.submit(cls, parsed, llm=llm, provider=resolved)
|
|
252
|
+
return RunCreated(
|
|
253
|
+
run_id=run.id,
|
|
254
|
+
status=run.status,
|
|
255
|
+
queue_position=manager.queue_position(run),
|
|
256
|
+
links={"self": f"/runs/{run.id}", "events": f"/runs/{run.id}/events"},
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
@app.get("/runs/{run_id}", response_model=RunView, tags=["runs"])
|
|
260
|
+
def get_run(run_id: str) -> RunView:
|
|
261
|
+
return view(find_run(run_id))
|
|
262
|
+
|
|
263
|
+
@app.get("/runs", response_model=list[RunView], tags=["runs"])
|
|
264
|
+
def list_runs(limit: int = 50) -> list[RunView]:
|
|
265
|
+
runs = sorted(manager.runs.values(), key=lambda r: r.created_at, reverse=True)
|
|
266
|
+
return [view(r) for r in runs[: max(1, min(limit, 500))]]
|
|
267
|
+
|
|
268
|
+
@app.delete("/runs/{run_id}", response_model=RunView, status_code=202, tags=["runs"])
|
|
269
|
+
async def cancel_run(run_id: str) -> RunView:
|
|
270
|
+
run = find_run(run_id)
|
|
271
|
+
await manager.cancel(run)
|
|
272
|
+
return view(run)
|
|
273
|
+
|
|
274
|
+
@app.get(
|
|
275
|
+
"/runs/{run_id}/events",
|
|
276
|
+
tags=["runs"],
|
|
277
|
+
response_class=EventSourceResponse,
|
|
278
|
+
responses={200: {"description": "Server-sent events: status, progress, result"}},
|
|
279
|
+
)
|
|
280
|
+
async def run_events(run_id: str, request: Request) -> EventSourceResponse:
|
|
281
|
+
run = find_run(run_id)
|
|
282
|
+
last = request.headers.get("last-event-id", "0")
|
|
283
|
+
after = int(last) if last.isdigit() else 0
|
|
284
|
+
|
|
285
|
+
async def stream() -> AsyncIterator[dict[str, str]]:
|
|
286
|
+
async for event in manager.events(run, after):
|
|
287
|
+
yield {"id": str(event.seq), "event": event.kind, "data": json.dumps(event.data)}
|
|
288
|
+
|
|
289
|
+
return EventSourceResponse(stream(), ping=15)
|
|
290
|
+
|
|
291
|
+
@app.exception_handler(HTTPException)
|
|
292
|
+
async def http_error(_: Request, exc: HTTPException) -> JSONResponse:
|
|
293
|
+
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
|
|
294
|
+
|
|
295
|
+
if ui_root is not None: # last, so every API route takes precedence
|
|
296
|
+
app.mount("/", StaticFiles(directory=ui_root, html=True), name="ui")
|
|
297
|
+
return app
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _bundled_ui() -> Path | None:
|
|
301
|
+
"""The web UI packed into the wheel at release time (absent in a source checkout)."""
|
|
302
|
+
bundled = Path(__file__).parent / "ui"
|
|
303
|
+
return bundled if (bundled / "index.html").is_file() else None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class _UIPages:
|
|
307
|
+
"""Send a browser's page loads (GET, asking for HTML) to the UI's index.html.
|
|
308
|
+
|
|
309
|
+
The UI's pages share paths with the API (``/agents``, ``/runs/<id>``), so a page load gets
|
|
310
|
+
the UI while the UI's own requests (JSON, events) reach the API. Plain ASGI on purpose:
|
|
311
|
+
FastAPI's decorator middleware wraps every response, which stalls the live event stream.
|
|
312
|
+
"""
|
|
313
|
+
|
|
314
|
+
API_PAGES = ("/docs", "/redoc", "/openapi.json")
|
|
315
|
+
|
|
316
|
+
def __init__(self, app: Any, root: Path) -> None:
|
|
317
|
+
self.app = app
|
|
318
|
+
self.root = root
|
|
319
|
+
self.index = root / "index.html"
|
|
320
|
+
|
|
321
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
322
|
+
if scope["type"] == "http" and scope.get("method") == "GET":
|
|
323
|
+
headers = dict(scope.get("headers") or [])
|
|
324
|
+
accept = headers.get(b"accept", b"").decode("latin-1")
|
|
325
|
+
path = str(scope.get("path", "/"))
|
|
326
|
+
if "text/html" in accept and not path.startswith(self.API_PAGES):
|
|
327
|
+
candidate = (self.root / path.lstrip("/")).resolve()
|
|
328
|
+
if not (candidate.is_file() and self.root in candidate.parents):
|
|
329
|
+
await FileResponse(self.index)(scope, receive, send)
|
|
330
|
+
return
|
|
331
|
+
await self.app(scope, receive, send)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _ui_root(ui_dir: Path) -> Path:
|
|
335
|
+
root = ui_dir.resolve()
|
|
336
|
+
if not (root / "index.html").is_file():
|
|
337
|
+
raise RuntimeError(f"MARGIN_API_UI_DIR has no index.html: {root}")
|
|
338
|
+
return root
|
margin_api/jobs.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Background runs: an in-memory store, two concurrency pools, events and cancellation.
|
|
2
|
+
|
|
3
|
+
A run moves through ``queued -> running -> done`` (or ``cancelled``). A run whose agent
|
|
4
|
+
fails still ends as ``done``: the failure is in its result (``status="error"``), not in the
|
|
5
|
+
run's state. Progress events are numbered and kept in a bounded buffer, so a client that
|
|
6
|
+
connects late (or reconnects) gets everything it missed.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import contextlib
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
from collections import deque
|
|
16
|
+
from collections.abc import AsyncIterator
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from datetime import UTC, datetime
|
|
19
|
+
from typing import Any, Literal
|
|
20
|
+
|
|
21
|
+
from margin_core import AgentRegistry, AgentResult, BaseAgent, ProgressEvent, RunContext
|
|
22
|
+
from margin_core.llm import LLMClient
|
|
23
|
+
from margin_core.logging import get_logger
|
|
24
|
+
from pydantic import BaseModel
|
|
25
|
+
|
|
26
|
+
from margin_api.settings import ApiSettings
|
|
27
|
+
|
|
28
|
+
RunStatus = Literal["queued", "running", "done", "cancelled"]
|
|
29
|
+
FINISHED: frozenset[str] = frozenset({"done", "cancelled"})
|
|
30
|
+
logger = get_logger("api.jobs")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class RunEvent:
|
|
35
|
+
seq: int
|
|
36
|
+
kind: Literal["status", "progress", "result"]
|
|
37
|
+
data: dict[str, Any]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Run:
|
|
42
|
+
id: str
|
|
43
|
+
agent_id: str
|
|
44
|
+
pool: str
|
|
45
|
+
status: RunStatus = "queued"
|
|
46
|
+
created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
|
|
47
|
+
started_at: datetime | None = None
|
|
48
|
+
finished_at: datetime | None = None
|
|
49
|
+
progress: ProgressEvent | None = None
|
|
50
|
+
result: AgentResult | None = None
|
|
51
|
+
events: deque[RunEvent] = field(default_factory=deque)
|
|
52
|
+
token: Any = None # CancellationToken, set when created
|
|
53
|
+
task: asyncio.Task[None] | None = None
|
|
54
|
+
llm: LLMClient | None = None # the model client for this run, if the agent uses one
|
|
55
|
+
llm_provider: str | None = None
|
|
56
|
+
llm_model: str | None = None
|
|
57
|
+
finished_monotonic: float | None = None
|
|
58
|
+
_seq: int = 0
|
|
59
|
+
_changed: asyncio.Event = field(default_factory=asyncio.Event)
|
|
60
|
+
|
|
61
|
+
def add_event(
|
|
62
|
+
self, kind: Literal["status", "progress", "result"], data: dict[str, Any]
|
|
63
|
+
) -> None:
|
|
64
|
+
self._seq += 1
|
|
65
|
+
self.events.append(RunEvent(self._seq, kind, data))
|
|
66
|
+
# wake every waiting subscriber, then arm a fresh event for the next change
|
|
67
|
+
self._changed.set()
|
|
68
|
+
self._changed = asyncio.Event()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class _Pool:
|
|
72
|
+
"""A FIFO concurrency limit that can report queue positions."""
|
|
73
|
+
|
|
74
|
+
def __init__(self, size: int) -> None:
|
|
75
|
+
self.semaphore = asyncio.Semaphore(size)
|
|
76
|
+
self.waiting: deque[str] = deque()
|
|
77
|
+
|
|
78
|
+
def position(self, run_id: str) -> int | None:
|
|
79
|
+
try:
|
|
80
|
+
return self.waiting.index(run_id) + 1
|
|
81
|
+
except ValueError:
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class RunManager:
|
|
86
|
+
def __init__(self, registry: AgentRegistry, settings: ApiSettings) -> None:
|
|
87
|
+
self.registry = registry
|
|
88
|
+
self.settings = settings
|
|
89
|
+
self.runs: dict[str, Run] = {}
|
|
90
|
+
self.pools = {
|
|
91
|
+
"llm": _Pool(settings.llm_concurrency), # runs on the local model (one GPU)
|
|
92
|
+
"other": _Pool(settings.other_concurrency), # everything else, hosted models too
|
|
93
|
+
}
|
|
94
|
+
self._sweeper: asyncio.Task[None] | None = None
|
|
95
|
+
|
|
96
|
+
# ---- lifecycle ------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
async def start(self) -> None:
|
|
99
|
+
self._sweeper = asyncio.create_task(self._sweep_forever())
|
|
100
|
+
|
|
101
|
+
async def stop(self) -> None:
|
|
102
|
+
if self._sweeper is not None:
|
|
103
|
+
self._sweeper.cancel()
|
|
104
|
+
for run in self.runs.values():
|
|
105
|
+
if run.task is not None and not run.task.done():
|
|
106
|
+
run.task.cancel()
|
|
107
|
+
|
|
108
|
+
# ---- runs -----------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
def submit(
|
|
111
|
+
self,
|
|
112
|
+
agent_cls: type[BaseAgent],
|
|
113
|
+
parsed: BaseModel,
|
|
114
|
+
*,
|
|
115
|
+
llm: LLMClient | None = None,
|
|
116
|
+
provider: str | None = None,
|
|
117
|
+
) -> Run:
|
|
118
|
+
"""Queue a run. ``llm`` is this run's model client (created from the current
|
|
119
|
+
settings, so a change in settings applies to the next run); ``provider`` decides the
|
|
120
|
+
queue: only runs on the local model wait for the single local GPU."""
|
|
121
|
+
from margin_core import CancellationToken
|
|
122
|
+
|
|
123
|
+
pool = "llm" if agent_cls.uses_llm and provider == "local" else "other"
|
|
124
|
+
run = Run(id=uuid.uuid4().hex, agent_id=agent_cls.id, pool=pool)
|
|
125
|
+
if agent_cls.uses_llm:
|
|
126
|
+
run.llm, run.llm_provider = llm, provider
|
|
127
|
+
run.llm_model = llm.model if llm is not None else None
|
|
128
|
+
run.token = CancellationToken()
|
|
129
|
+
run.events = deque(maxlen=self.settings.event_buffer)
|
|
130
|
+
self.runs[run.id] = run
|
|
131
|
+
self.pools[pool].waiting.append(run.id)
|
|
132
|
+
run.add_event("status", {"status": "queued"})
|
|
133
|
+
run.task = asyncio.create_task(self._execute(run, agent_cls, parsed))
|
|
134
|
+
self._enforce_capacity()
|
|
135
|
+
return run
|
|
136
|
+
|
|
137
|
+
def get(self, run_id: str) -> Run | None:
|
|
138
|
+
return self.runs.get(run_id)
|
|
139
|
+
|
|
140
|
+
def queue_position(self, run: Run) -> int | None:
|
|
141
|
+
return self.pools[run.pool].position(run.id) if run.status == "queued" else None
|
|
142
|
+
|
|
143
|
+
async def _execute(self, run: Run, agent_cls: type[BaseAgent], parsed: BaseModel) -> None:
|
|
144
|
+
pool = self.pools[run.pool]
|
|
145
|
+
try:
|
|
146
|
+
async with pool.semaphore:
|
|
147
|
+
with contextlib.suppress(ValueError):
|
|
148
|
+
pool.waiting.remove(run.id)
|
|
149
|
+
if run.token.cancelled:
|
|
150
|
+
self._finish(run, None, cancelled=True)
|
|
151
|
+
return
|
|
152
|
+
run.status = "running"
|
|
153
|
+
run.started_at = datetime.now(UTC)
|
|
154
|
+
run.add_event("status", {"status": "running"})
|
|
155
|
+
|
|
156
|
+
def on_progress(event: ProgressEvent) -> None:
|
|
157
|
+
run.progress = event
|
|
158
|
+
run.add_event("progress", event.model_dump(mode="json"))
|
|
159
|
+
|
|
160
|
+
agent = agent_cls(llm=run.llm)
|
|
161
|
+
ctx = RunContext(progress=on_progress, cancel_token=run.token)
|
|
162
|
+
result = await agent.execute(parsed, ctx)
|
|
163
|
+
self._finish(run, result, cancelled=run.token.cancelled)
|
|
164
|
+
except asyncio.CancelledError:
|
|
165
|
+
self._finish(run, None, cancelled=True)
|
|
166
|
+
except Exception as exc: # noqa: BLE001 - never lose a run silently
|
|
167
|
+
logger.exception("Run %s crashed outside the agent", run.id)
|
|
168
|
+
self._finish(
|
|
169
|
+
run,
|
|
170
|
+
AgentResult(
|
|
171
|
+
agent_id=run.agent_id,
|
|
172
|
+
agent_version="unknown",
|
|
173
|
+
status="error",
|
|
174
|
+
summary="The server failed to run this agent.",
|
|
175
|
+
error=str(exc),
|
|
176
|
+
), # fmt: skip
|
|
177
|
+
cancelled=False,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
def _finish(self, run: Run, result: AgentResult | None, *, cancelled: bool) -> None:
|
|
181
|
+
if run.status in FINISHED:
|
|
182
|
+
return
|
|
183
|
+
with contextlib.suppress(ValueError):
|
|
184
|
+
self.pools[run.pool].waiting.remove(run.id)
|
|
185
|
+
run.status = "cancelled" if cancelled else "done"
|
|
186
|
+
run.result = result
|
|
187
|
+
run.finished_at = datetime.now(UTC)
|
|
188
|
+
run.finished_monotonic = time.monotonic()
|
|
189
|
+
run.add_event("status", {"status": run.status})
|
|
190
|
+
run.add_event(
|
|
191
|
+
"result",
|
|
192
|
+
{"status": run.status, "result": result.model_dump(mode="json") if result else None},
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
async def cancel(self, run: Run) -> None:
|
|
196
|
+
"""Ask the run to stop; force it after the grace period."""
|
|
197
|
+
if run.status in FINISHED:
|
|
198
|
+
return
|
|
199
|
+
run.token.cancel()
|
|
200
|
+
if run.status == "queued":
|
|
201
|
+
if run.task is not None:
|
|
202
|
+
run.task.cancel()
|
|
203
|
+
self._finish(run, None, cancelled=True)
|
|
204
|
+
return
|
|
205
|
+
asyncio.create_task(self._force_after_grace(run))
|
|
206
|
+
|
|
207
|
+
async def _force_after_grace(self, run: Run) -> None:
|
|
208
|
+
await asyncio.sleep(self.settings.cancel_grace_s)
|
|
209
|
+
if run.status not in FINISHED and run.task is not None:
|
|
210
|
+
logger.warning("Run %s ignored cancellation; stopping its task", run.id)
|
|
211
|
+
run.task.cancel()
|
|
212
|
+
|
|
213
|
+
# ---- events ---------------------------------------------------------------------
|
|
214
|
+
|
|
215
|
+
async def events(self, run: Run, after: int = 0) -> AsyncIterator[RunEvent]:
|
|
216
|
+
"""Yield events with ``seq > after`` (buffered first), until the result event."""
|
|
217
|
+
while True:
|
|
218
|
+
pending = [e for e in list(run.events) if e.seq > after]
|
|
219
|
+
for event in pending:
|
|
220
|
+
yield event
|
|
221
|
+
after = event.seq
|
|
222
|
+
if event.kind == "result":
|
|
223
|
+
return
|
|
224
|
+
if run.status in FINISHED and not pending:
|
|
225
|
+
return
|
|
226
|
+
await run._changed.wait()
|
|
227
|
+
|
|
228
|
+
# ---- housekeeping -----------------------------------------------------------------
|
|
229
|
+
|
|
230
|
+
def _enforce_capacity(self) -> None:
|
|
231
|
+
finished = sorted(
|
|
232
|
+
(r for r in self.runs.values() if r.status in FINISHED),
|
|
233
|
+
key=lambda r: r.finished_monotonic or 0.0,
|
|
234
|
+
)
|
|
235
|
+
while len(self.runs) > self.settings.max_runs and finished:
|
|
236
|
+
self.runs.pop(finished.pop(0).id, None)
|
|
237
|
+
|
|
238
|
+
def sweep(self) -> int:
|
|
239
|
+
"""Forget finished runs older than the TTL. Returns how many were removed."""
|
|
240
|
+
now = time.monotonic()
|
|
241
|
+
expired = [
|
|
242
|
+
r.id for r in self.runs.values()
|
|
243
|
+
if r.finished_monotonic is not None
|
|
244
|
+
and now - r.finished_monotonic > self.settings.result_ttl_s
|
|
245
|
+
] # fmt: skip
|
|
246
|
+
for run_id in expired:
|
|
247
|
+
self.runs.pop(run_id, None)
|
|
248
|
+
return len(expired)
|
|
249
|
+
|
|
250
|
+
async def _sweep_forever(self) -> None:
|
|
251
|
+
while True:
|
|
252
|
+
await asyncio.sleep(max(1.0, min(60.0, self.settings.result_ttl_s)))
|
|
253
|
+
self.sweep()
|