modelcall 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.
- modelcall/__init__.py +3 -0
- modelcall/__main__.py +203 -0
- modelcall/agent.py +322 -0
- modelcall/agent_tools.py +465 -0
- modelcall/app.py +137 -0
- modelcall/batches.py +134 -0
- modelcall/checker.py +534 -0
- modelcall/cli.py +636 -0
- modelcall/doctor.py +113 -0
- modelcall/evaluator.py +174 -0
- modelcall/export.py +244 -0
- modelcall/inference.py +710 -0
- modelcall/matcher.py +276 -0
- modelcall/mcp_server.py +218 -0
- modelcall/migrate.py +120 -0
- modelcall/profiling.py +186 -0
- modelcall/providers/__init__.py +20 -0
- modelcall/providers/anthropic.py +223 -0
- modelcall/providers/base.py +89 -0
- modelcall/providers/fake.py +140 -0
- modelcall/providers/openai_compat.py +345 -0
- modelcall/resolver.py +303 -0
- modelcall/review.py +354 -0
- modelcall/schema.py +107 -0
- modelcall/serve.py +15 -0
- modelcall/settings.py +50 -0
- modelcall/sql/bridge/http.sql +53 -0
- modelcall/sql/bridge/plpython3u.sql +56 -0
- modelcall/sql/install.sql +26 -0
- modelcall/sql/migrations/0001_core.sql +589 -0
- modelcall/sql/migrations/0002_tasks.sql +941 -0
- modelcall/sql/migrations/0003_agent.sql +644 -0
- modelcall/sql/migrations/0004_master_data.sql +585 -0
- modelcall/sql/migrations/0005_mappings.sql +900 -0
- modelcall/sql/migrations/0006_providers.sql +32 -0
- modelcall/sql/migrations/0007_ledger.sql +735 -0
- modelcall/sql/migrations/0008_evaluation.sql +919 -0
- modelcall/sql/migrations/0009_semantics.sql +852 -0
- modelcall/sql/migrations/0010_conformance.sql +779 -0
- modelcall/sql/migrations/0011_standardization.sql +540 -0
- modelcall/sql/migrations/0012_entities.sql +686 -0
- modelcall/sql/migrations/0013_check_controls.sql +107 -0
- modelcall/sql/migrations/0014_preview_categories.sql +37 -0
- modelcall/sql/migrations/0015_agent_and_rules.sql +385 -0
- modelcall/sql/migrations/0016_check_population.sql +82 -0
- modelcall/sql/migrations/0017_rename_to_modelcall.sql +125 -0
- modelcall/sql/migrations/0018_routing.sql +260 -0
- modelcall/sql/migrations/0019_measured_routing.sql +207 -0
- modelcall/sql/migrations/0020_watch_costs_categories.sql +271 -0
- modelcall/text.py +45 -0
- modelcall/worker.py +307 -0
- modelcall-0.1.0.dist-info/METADATA +257 -0
- modelcall-0.1.0.dist-info/RECORD +57 -0
- modelcall-0.1.0.dist-info/WHEEL +5 -0
- modelcall-0.1.0.dist-info/entry_points.txt +2 -0
- modelcall-0.1.0.dist-info/licenses/LICENSE +202 -0
- modelcall-0.1.0.dist-info/top_level.txt +1 -0
modelcall/batches.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Provider batch mode for attached tasks (mod.attach(..., mode => 'batch')).
|
|
2
|
+
|
|
3
|
+
Claimed items of a batch-mode attachment are answered from the cache where
|
|
4
|
+
possible; the rest are submitted to the provider's batch API (Anthropic
|
|
5
|
+
Message Batches, OpenAI Batch) at about half price. The items move to a new
|
|
6
|
+
lease token with a 25-hour lease, recorded with the batch in
|
|
7
|
+
mod.provider_batches, so any worker can poll it later. When the batch has
|
|
8
|
+
ended, its results are interpreted and recorded like any other call and go
|
|
9
|
+
through the same mod.complete_work path, so the source-version checks,
|
|
10
|
+
retries and budgets are unchanged. If the batch never ends, the lease expires
|
|
11
|
+
and the items are claimed (and submitted) again.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from psycopg.rows import dict_row
|
|
18
|
+
from psycopg.types.json import Jsonb
|
|
19
|
+
|
|
20
|
+
from .inference import Engine, Prepared, RequestError, Result, sha256
|
|
21
|
+
from .providers import ProviderError
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger("modelcall.batches")
|
|
24
|
+
|
|
25
|
+
BATCH_LEASE_SECONDS = 25 * 3600
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class BatchManager:
|
|
29
|
+
def __init__(self, engine: Engine, worker_name: str, poll_seconds: float = 60.0):
|
|
30
|
+
self.engine = engine
|
|
31
|
+
self.name = worker_name
|
|
32
|
+
self.poll_seconds = poll_seconds
|
|
33
|
+
|
|
34
|
+
async def submit(self, token: Any, attachment: int, task: str, items: list[dict],
|
|
35
|
+
result_row) -> list[dict]:
|
|
36
|
+
"""Returns results to complete now (cache hits and failures); submits the rest."""
|
|
37
|
+
try:
|
|
38
|
+
spec = await self.engine.load_task(task)
|
|
39
|
+
profile = await self.engine.load_model(
|
|
40
|
+
await self.engine.choose_model(spec, None, [item["input"] for item in items]))
|
|
41
|
+
provider = self.engine.provider_for(profile)
|
|
42
|
+
except (RequestError, ProviderError) as exc:
|
|
43
|
+
code = getattr(exc, "code", "config_error")
|
|
44
|
+
failure = Result(status="error", error_code=code, error=str(getattr(exc, "message", exc)))
|
|
45
|
+
return [result_row(item, attachment, failure) for item in items]
|
|
46
|
+
if not hasattr(provider, "submit_batch"):
|
|
47
|
+
failure = Result(status="error", error_code="unsupported",
|
|
48
|
+
error=f"provider {profile.provider} has no batch API; attach with mode => 'online'")
|
|
49
|
+
return [result_row(item, attachment, failure) for item in items]
|
|
50
|
+
|
|
51
|
+
prepared = {item["work_id"]: self.engine.prepare(spec, profile, item["input"]) for item in items}
|
|
52
|
+
hits = await self.engine.cache_lookup([p.fingerprint for p in prepared.values()])
|
|
53
|
+
cached = [item for item in items if prepared[item["work_id"]].fingerprint in hits]
|
|
54
|
+
submit = [item for item in items if prepared[item["work_id"]].fingerprint not in hits]
|
|
55
|
+
now: list[dict] = []
|
|
56
|
+
if cached: # answered from the cache right away, through the normal path
|
|
57
|
+
results = await self.engine.run(spec, [item["input"] for item in cached], caller=f"worker:{self.name}",
|
|
58
|
+
source=f"attachment:{attachment}")
|
|
59
|
+
now = [result_row(item, attachment, result, spec.task_version) for item, result in zip(cached, results)]
|
|
60
|
+
if not submit:
|
|
61
|
+
return now
|
|
62
|
+
requests = [{"custom_id": f"w{item['work_id']}", "system": prepared[item["work_id"]].system,
|
|
63
|
+
"messages": [{"role": "user", "content": prepared[item["work_id"]].user}],
|
|
64
|
+
"schema": prepared[item["work_id"]].schema, "strict": prepared[item["work_id"]].strict}
|
|
65
|
+
for item in submit]
|
|
66
|
+
try:
|
|
67
|
+
batch_id = await provider.submit_batch(requests)
|
|
68
|
+
except ProviderError as exc:
|
|
69
|
+
failure = Result(status="error", error_code=exc.code, error=str(exc))
|
|
70
|
+
return now + [result_row(item, attachment, failure) for item in submit]
|
|
71
|
+
|
|
72
|
+
async with self.engine.pool.connection() as conn:
|
|
73
|
+
cur = conn.cursor(row_factory=dict_row)
|
|
74
|
+
await cur.execute("SELECT mod.transfer_lease(%s, %s, make_interval(secs => %s)) AS token",
|
|
75
|
+
(token, [i["work_id"] for i in submit], BATCH_LEASE_SECONDS))
|
|
76
|
+
fresh = (await cur.fetchone())["token"]
|
|
77
|
+
await cur.execute(
|
|
78
|
+
"""INSERT INTO mod.provider_batches (provider_batch_id, provider, model, model_version, task, task_version,
|
|
79
|
+
attachment_id, lease_token, items, next_poll_at)
|
|
80
|
+
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, now() + make_interval(secs => %s))""",
|
|
81
|
+
(batch_id, profile.provider, profile.name, profile.version, task, spec.task_version, attachment, fresh,
|
|
82
|
+
Jsonb([{"work_id": i["work_id"], "input_hash": i["input_hash"], "custom_id": f"w{i['work_id']}",
|
|
83
|
+
"fingerprint": prepared[i["work_id"]].fingerprint,
|
|
84
|
+
"input_sha": sha256(i["input"])} for i in submit]),
|
|
85
|
+
self.poll_seconds))
|
|
86
|
+
log.info("attachment %s: submitted %s items as provider batch %s", attachment, len(submit), batch_id)
|
|
87
|
+
return now
|
|
88
|
+
|
|
89
|
+
async def poll(self, force: bool = False, max_batches: int = 5) -> int:
|
|
90
|
+
"""Checks submitted batches; completes the items of those that ended. Returns items completed."""
|
|
91
|
+
async with self.engine.pool.connection() as conn:
|
|
92
|
+
cur = conn.cursor(row_factory=dict_row)
|
|
93
|
+
await cur.execute("SELECT * FROM mod.claim_batch_polls(%s, make_interval(secs => %s), %s, %s)",
|
|
94
|
+
(max_batches, self.poll_seconds, self.name, force))
|
|
95
|
+
batches = await cur.fetchall()
|
|
96
|
+
done = 0
|
|
97
|
+
for batch in batches:
|
|
98
|
+
try:
|
|
99
|
+
done += await self._poll_one(batch)
|
|
100
|
+
except Exception:
|
|
101
|
+
log.exception("provider batch %s: poll failed; retrying later", batch["provider_batch_id"])
|
|
102
|
+
return done
|
|
103
|
+
|
|
104
|
+
async def _poll_one(self, batch: dict) -> int:
|
|
105
|
+
profile = await self.engine.load_model(batch["model"])
|
|
106
|
+
provider = self.engine.provider_for(profile)
|
|
107
|
+
if await provider.batch_status(batch["provider_batch_id"]) != "ended":
|
|
108
|
+
return 0
|
|
109
|
+
outcomes = await provider.batch_results(batch["provider_batch_id"])
|
|
110
|
+
spec = await self.engine.load_task(batch["task"], batch["task_version"])
|
|
111
|
+
results = []
|
|
112
|
+
for item in batch["items"]:
|
|
113
|
+
outcome = outcomes.get(item["custom_id"])
|
|
114
|
+
prepared = Prepared(input_value=None, system="", user="", fingerprint=item["fingerprint"],
|
|
115
|
+
schema=self.engine.prepare(spec, profile, "").schema, strict=False, shots=[],
|
|
116
|
+
input_sha=item["input_sha"])
|
|
117
|
+
result = await self.engine.record_completion(
|
|
118
|
+
prepared, outcome if not isinstance(outcome, ProviderError) else None,
|
|
119
|
+
outcome if isinstance(outcome, ProviderError) else None,
|
|
120
|
+
profile=profile, spec=spec, caller=f"batch:{self.name}", source=f"attachment:{batch['attachment_id']}",
|
|
121
|
+
batch=True)
|
|
122
|
+
from .worker import _result # the same row shape the online path sends
|
|
123
|
+
|
|
124
|
+
results.append(_result({"work_id": item["work_id"], "input_hash": item["input_hash"]},
|
|
125
|
+
batch["attachment_id"], result, spec.task_version))
|
|
126
|
+
async with self.engine.pool.connection() as conn:
|
|
127
|
+
await conn.execute("CALL mod.complete_work(%s, %s, make_interval(secs => %s), %s)",
|
|
128
|
+
(batch["lease_token"], Jsonb(results), self.engine.settings.worker_retry_base_seconds,
|
|
129
|
+
self.engine.settings.worker_max_attempts))
|
|
130
|
+
await conn.execute("UPDATE mod.provider_batches SET state = 'done', finished_at = now() WHERE id = %s",
|
|
131
|
+
(batch["id"],))
|
|
132
|
+
log.info("provider batch %s ended: %s items", batch["provider_batch_id"], len(results))
|
|
133
|
+
return len(results)
|
|
134
|
+
|