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
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Model settings over HTTP, for the web UI: which provider and model runs use, the keys
|
|
2
|
+
(never sent back, only whether one is set and its last four characters), the models each
|
|
3
|
+
provider offers, and a connection check. Changes are saved in the user's settings file and
|
|
4
|
+
apply to the next run; nothing needs a restart."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from fastapi import APIRouter, HTTPException
|
|
11
|
+
from margin_core.config import (
|
|
12
|
+
Source,
|
|
13
|
+
get_settings,
|
|
14
|
+
save_user_config,
|
|
15
|
+
setting_sources,
|
|
16
|
+
user_config_path,
|
|
17
|
+
)
|
|
18
|
+
from margin_core.errors import LLMError
|
|
19
|
+
from margin_core.llm.catalog import PROVIDERS, check_connection, list_models
|
|
20
|
+
from margin_core.llm.factory import DEFAULT_MODELS, PROVIDER_MODEL_SETTING, resolve_model
|
|
21
|
+
from pydantic import BaseModel, Field, SecretStr
|
|
22
|
+
|
|
23
|
+
ProviderId = Literal["local", "anthropic", "openai"]
|
|
24
|
+
KEY_SETTING: dict[str, str] = {
|
|
25
|
+
"local": "local_llm_api_key",
|
|
26
|
+
"anthropic": "anthropic_api_key",
|
|
27
|
+
"openai": "openai_api_key",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ProviderView(BaseModel):
|
|
32
|
+
id: ProviderId
|
|
33
|
+
label: str
|
|
34
|
+
needs_key: bool
|
|
35
|
+
on_device: bool = Field(
|
|
36
|
+
description="False: prompts, such as samples of code, leave this machine."
|
|
37
|
+
)
|
|
38
|
+
default_model: str
|
|
39
|
+
model: str = Field(description="The model runs use with this provider.")
|
|
40
|
+
model_source: Source
|
|
41
|
+
key_set: bool
|
|
42
|
+
key_hint: str | None = Field(description="Last four characters of the key, never the key.")
|
|
43
|
+
key_source: Source
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class LLMSettingsView(BaseModel):
|
|
47
|
+
provider: ProviderId
|
|
48
|
+
provider_source: Source
|
|
49
|
+
local_base_url: str
|
|
50
|
+
local_base_url_source: Source
|
|
51
|
+
max_cost_usd: float = Field(description="Spending cap per run, for hosted providers.")
|
|
52
|
+
providers: list[ProviderView]
|
|
53
|
+
saving_enabled: bool
|
|
54
|
+
settings_file: str | None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class LLMSettingsUpdate(BaseModel):
|
|
58
|
+
"""Only the fields present change. For models and keys, an empty string removes the
|
|
59
|
+
saved value (the next source in line applies again)."""
|
|
60
|
+
|
|
61
|
+
model_config = {"extra": "forbid"}
|
|
62
|
+
|
|
63
|
+
provider: ProviderId | None = None
|
|
64
|
+
local_base_url: str | None = None
|
|
65
|
+
models: dict[ProviderId, str] | None = None
|
|
66
|
+
keys: dict[ProviderId, str] | None = None
|
|
67
|
+
max_cost_usd: float | None = Field(default=None, ge=0)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ModelList(BaseModel):
|
|
71
|
+
provider: ProviderId
|
|
72
|
+
models: list[str]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ConnectionRequest(BaseModel):
|
|
76
|
+
model_config = {"extra": "forbid"}
|
|
77
|
+
|
|
78
|
+
provider: ProviderId | None = None
|
|
79
|
+
model: str | None = None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class ConnectionResult(BaseModel):
|
|
83
|
+
ok: bool
|
|
84
|
+
provider: str
|
|
85
|
+
model: str
|
|
86
|
+
latency_ms: int | None
|
|
87
|
+
message: str
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _hint(secret: SecretStr | None) -> str | None:
|
|
91
|
+
value = secret.get_secret_value() if secret else ""
|
|
92
|
+
return f"…{value[-4:]}" if len(value) >= 8 else ("set" if value else None)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def current_view() -> LLMSettingsView:
|
|
96
|
+
settings = get_settings()
|
|
97
|
+
sources = setting_sources()
|
|
98
|
+
provider = settings.default_llm_provider.lower()
|
|
99
|
+
views = []
|
|
100
|
+
for p in PROVIDERS:
|
|
101
|
+
key = getattr(settings, KEY_SETTING[p.id])
|
|
102
|
+
model_field = PROVIDER_MODEL_SETTING[p.id]
|
|
103
|
+
views.append(
|
|
104
|
+
ProviderView(
|
|
105
|
+
id=p.id, # type: ignore[arg-type]
|
|
106
|
+
label=p.label,
|
|
107
|
+
needs_key=p.needs_key,
|
|
108
|
+
on_device=p.on_device,
|
|
109
|
+
default_model=DEFAULT_MODELS[p.id],
|
|
110
|
+
model=resolve_model(p.id, settings),
|
|
111
|
+
model_source=sources.get(model_field, "default"),
|
|
112
|
+
key_set=bool(key and key.get_secret_value()),
|
|
113
|
+
key_hint=_hint(key),
|
|
114
|
+
key_source=sources.get(KEY_SETTING[p.id], "default"),
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
path = user_config_path()
|
|
118
|
+
return LLMSettingsView(
|
|
119
|
+
provider=provider if provider in KEY_SETTING else "local", # type: ignore[arg-type]
|
|
120
|
+
provider_source=sources["default_llm_provider"],
|
|
121
|
+
local_base_url=settings.local_llm_base_url,
|
|
122
|
+
local_base_url_source=sources["local_llm_base_url"],
|
|
123
|
+
max_cost_usd=settings.max_cost_usd,
|
|
124
|
+
providers=views,
|
|
125
|
+
saving_enabled=path is not None,
|
|
126
|
+
settings_file=str(path) if path else None,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
router = APIRouter(prefix="/settings/llm", tags=["settings"])
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@router.get("", response_model=LLMSettingsView)
|
|
134
|
+
def get_llm_settings() -> LLMSettingsView:
|
|
135
|
+
return current_view()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@router.put("", response_model=LLMSettingsView)
|
|
139
|
+
def update_llm_settings(update: LLMSettingsUpdate) -> LLMSettingsView:
|
|
140
|
+
changes: dict[str, object] = {}
|
|
141
|
+
if update.provider is not None:
|
|
142
|
+
changes["default_llm_provider"] = update.provider
|
|
143
|
+
if update.local_base_url is not None:
|
|
144
|
+
url = update.local_base_url.strip()
|
|
145
|
+
if url and not url.startswith(("http://", "https://")):
|
|
146
|
+
raise HTTPException(422, "The server address must start with http:// or https://")
|
|
147
|
+
changes["local_llm_base_url"] = url
|
|
148
|
+
for provider, model in (update.models or {}).items():
|
|
149
|
+
changes[PROVIDER_MODEL_SETTING[provider]] = model.strip()
|
|
150
|
+
for provider, key in (update.keys or {}).items():
|
|
151
|
+
changes[KEY_SETTING[provider]] = key.strip()
|
|
152
|
+
if update.max_cost_usd is not None:
|
|
153
|
+
changes["max_cost_usd"] = update.max_cost_usd
|
|
154
|
+
if changes:
|
|
155
|
+
try:
|
|
156
|
+
save_user_config(changes)
|
|
157
|
+
except RuntimeError as exc: # saving is turned off
|
|
158
|
+
raise HTTPException(409, str(exc)) from exc
|
|
159
|
+
return current_view()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@router.get("/models", response_model=ModelList)
|
|
163
|
+
async def get_models(provider: ProviderId) -> ModelList:
|
|
164
|
+
try:
|
|
165
|
+
return ModelList(provider=provider, models=await list_models(provider))
|
|
166
|
+
except LLMError as exc:
|
|
167
|
+
raise HTTPException(502, str(exc)) from exc
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@router.post("/test", response_model=ConnectionResult)
|
|
171
|
+
async def test_connection(request: ConnectionRequest) -> ConnectionResult:
|
|
172
|
+
check = await check_connection(request.provider, request.model)
|
|
173
|
+
return ConnectionResult(**check.__dict__)
|
margin_api/main.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Entry point: ``margin-api`` starts the server (``MARGIN_API_HOST``/``MARGIN_API_PORT``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from margin_api.app import create_app
|
|
6
|
+
from margin_api.settings import load_settings
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def run() -> None:
|
|
10
|
+
import uvicorn
|
|
11
|
+
|
|
12
|
+
settings = load_settings()
|
|
13
|
+
uvicorn.run(create_app(settings=settings), host=settings.host, port=settings.port)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
if __name__ == "__main__":
|
|
17
|
+
run()
|
margin_api/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Marker file for PEP 561
|
margin_api/settings.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""API server settings, from ``MARGIN_API_*`` environment variables (and ``.env``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ApiSettings(BaseSettings):
|
|
11
|
+
model_config = SettingsConfigDict(env_prefix="MARGIN_API_", extra="ignore")
|
|
12
|
+
|
|
13
|
+
host: str = "127.0.0.1" # not exposed on the network unless you choose to
|
|
14
|
+
port: int = 8000
|
|
15
|
+
cors_origins: list[str] = ["http://localhost:3000", "http://127.0.0.1:3000"]
|
|
16
|
+
# Host names the API answers to (protects against DNS rebinding). Add yours if you
|
|
17
|
+
# change ``host`` to expose the API on a network.
|
|
18
|
+
allowed_hosts: list[str] = ["127.0.0.1", "localhost"]
|
|
19
|
+
# A built web UI (ui/dist) to serve from the same address, so one server is the whole app.
|
|
20
|
+
ui_dir: str | None = None
|
|
21
|
+
max_body_bytes: int = 1_000_000
|
|
22
|
+
llm_concurrency: int = 1 # runs of agents that use a model (a local model has one GPU)
|
|
23
|
+
other_concurrency: int = 4 # runs of agents that do not
|
|
24
|
+
result_ttl_s: float = 3600.0 # finished runs are forgotten after this
|
|
25
|
+
max_runs: int = 1000 # stored runs, finished ones are dropped oldest first
|
|
26
|
+
event_buffer: int = 200 # progress events kept per run for late subscribers
|
|
27
|
+
cancel_grace_s: float = 30.0 # time a cancelled run gets to stop on its own
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load_settings() -> ApiSettings:
|
|
31
|
+
env_file = os.environ.get("MARGIN_ENV_FILE", ".env")
|
|
32
|
+
return ApiSettings(_env_file=env_file or None) # type: ignore[call-arg]
|