offpeak 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.
- offpeak/__init__.py +37 -0
- offpeak/client.py +223 -0
- offpeak/deadline.py +84 -0
- offpeak/job.py +109 -0
- offpeak/prices.py +68 -0
- offpeak/venues/__init__.py +5 -0
- offpeak/venues/anthropic_batch.py +141 -0
- offpeak/venues/base.py +58 -0
- offpeak/venues/openai_batch.py +149 -0
- offpeak-0.1.0.dist-info/METADATA +144 -0
- offpeak-0.1.0.dist-info/RECORD +13 -0
- offpeak-0.1.0.dist-info/WHEEL +4 -0
- offpeak-0.1.0.dist-info/licenses/LICENSE +202 -0
offpeak/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""offpeak — deadline-priced inference.
|
|
2
|
+
|
|
3
|
+
Same model, same tokens, a different hour. Give AI work a deadline and run it
|
|
4
|
+
on the cheapest venue that keeps the SLA — provider batch tiers (−50%) today.
|
|
5
|
+
|
|
6
|
+
import offpeak
|
|
7
|
+
|
|
8
|
+
jobs = [offpeak.job("claude-haiku-4-5", f"Summarize:\\n\\n{d}") for d in docs]
|
|
9
|
+
results = offpeak.run(jobs, deadline="06:00")
|
|
10
|
+
print(offpeak.receipt(results))
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from . import prices
|
|
14
|
+
from .client import Settlement, default_venues, receipt, run
|
|
15
|
+
from .deadline import parse_deadline, seconds_until
|
|
16
|
+
from .job import Job, Receipt, Result, Status, job
|
|
17
|
+
from .venues.base import BatchState, Venue
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"job",
|
|
23
|
+
"run",
|
|
24
|
+
"receipt",
|
|
25
|
+
"Job",
|
|
26
|
+
"Result",
|
|
27
|
+
"Receipt",
|
|
28
|
+
"Settlement",
|
|
29
|
+
"Status",
|
|
30
|
+
"Venue",
|
|
31
|
+
"BatchState",
|
|
32
|
+
"parse_deadline",
|
|
33
|
+
"seconds_until",
|
|
34
|
+
"default_venues",
|
|
35
|
+
"prices",
|
|
36
|
+
"__version__",
|
|
37
|
+
]
|
offpeak/client.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""The v0 desk: portfolio-submit jobs to batch venues, watch the deadline,
|
|
2
|
+
fall back to sync if the batch won't make it, settle a receipt.
|
|
3
|
+
|
|
4
|
+
This is deliberately simple — deadline risk is a buffer, not a forecast. The
|
|
5
|
+
hosted desk adds queue-latency forecasting, cross-venue portfolio placement,
|
|
6
|
+
own-GPU off-peak windows, and carbon-aware scheduling on the same interface.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
|
|
15
|
+
from .deadline import parse_deadline, seconds_until
|
|
16
|
+
from .job import Job, Receipt, Result, Status
|
|
17
|
+
from .prices import PRICE_SHEET_DATE
|
|
18
|
+
from .venues.base import Venue
|
|
19
|
+
|
|
20
|
+
__all__ = ["run", "receipt", "Settlement", "default_venues"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def default_venues() -> list[Venue]:
|
|
24
|
+
"""Provider batch tiers, tried in order. SDKs import lazily on first use."""
|
|
25
|
+
from .venues.anthropic_batch import AnthropicBatch
|
|
26
|
+
from .venues.openai_batch import OpenAIBatch
|
|
27
|
+
|
|
28
|
+
return [AnthropicBatch(), OpenAIBatch()]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _usage_tokens(raw: object) -> tuple[int, int]:
|
|
32
|
+
if not isinstance(raw, dict):
|
|
33
|
+
return 0, 0
|
|
34
|
+
input_tokens = raw.get("input_tokens", raw.get("prompt_tokens", 0)) or 0
|
|
35
|
+
output_tokens = raw.get("output_tokens", raw.get("completion_tokens", 0)) or 0
|
|
36
|
+
return int(input_tokens), int(output_tokens)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _pick_venue(model: str, venues: list[Venue]) -> Venue:
|
|
40
|
+
for venue in venues:
|
|
41
|
+
if venue.supports(model):
|
|
42
|
+
return venue
|
|
43
|
+
known = ", ".join(v.name for v in venues)
|
|
44
|
+
raise ValueError(f"no venue supports model {model!r} (venues: {known})")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def run(
|
|
48
|
+
jobs: Job | list[Job],
|
|
49
|
+
deadline: object,
|
|
50
|
+
*,
|
|
51
|
+
venues: list[Venue] | None = None,
|
|
52
|
+
fallback: str = "sync",
|
|
53
|
+
poll_interval: float | None = None,
|
|
54
|
+
risk_buffer: float | None = None,
|
|
55
|
+
) -> list[Result]:
|
|
56
|
+
"""Run *jobs* against *deadline* on the cheapest supporting venue.
|
|
57
|
+
|
|
58
|
+
Submits each job to its venue's batch tier, polls until everything lands,
|
|
59
|
+
and — if the batch has not completed by the time the remaining window
|
|
60
|
+
shrinks to ``risk_buffer`` seconds — cancels and re-runs the stragglers
|
|
61
|
+
synchronously at list price so the deadline is met (``fallback="sync"``,
|
|
62
|
+
the default; ``fallback="none"`` reports them failed instead).
|
|
63
|
+
|
|
64
|
+
Returns one :class:`Result` per job, in input order, each with a
|
|
65
|
+
:class:`Receipt`.
|
|
66
|
+
"""
|
|
67
|
+
job_list = [jobs] if isinstance(jobs, Job) else list(jobs)
|
|
68
|
+
if not job_list:
|
|
69
|
+
return []
|
|
70
|
+
resolved = parse_deadline(deadline)
|
|
71
|
+
window = seconds_until(resolved)
|
|
72
|
+
if risk_buffer is None:
|
|
73
|
+
risk_buffer = max(60.0, min(600.0, 0.15 * window))
|
|
74
|
+
venue_list = venues if venues is not None else default_venues()
|
|
75
|
+
|
|
76
|
+
groups: dict[str, tuple[Venue, list[Job]]] = {}
|
|
77
|
+
for j in job_list:
|
|
78
|
+
venue = _pick_venue(j.model, venue_list)
|
|
79
|
+
groups.setdefault(venue.name, (venue, []))[1].append(j)
|
|
80
|
+
|
|
81
|
+
submitted_at = datetime.now().astimezone()
|
|
82
|
+
pending: dict[str, str] = {} # venue name -> batch handle
|
|
83
|
+
for name, (venue, group_jobs) in groups.items():
|
|
84
|
+
pending[name] = venue.submit(group_jobs)
|
|
85
|
+
for j in group_jobs:
|
|
86
|
+
j.status = Status.SUBMITTED
|
|
87
|
+
|
|
88
|
+
collected: dict[str, Result] = {}
|
|
89
|
+
fell_back: set[str] = set()
|
|
90
|
+
|
|
91
|
+
while pending:
|
|
92
|
+
for name in list(pending):
|
|
93
|
+
venue, group_jobs = groups[name]
|
|
94
|
+
state = venue.status(pending[name])
|
|
95
|
+
if state.status == "completed":
|
|
96
|
+
collected.update(venue.collect(pending[name]))
|
|
97
|
+
del pending[name]
|
|
98
|
+
elif state.status in ("failed", "cancelled"):
|
|
99
|
+
del pending[name] # jobs surface below as fallback or errors
|
|
100
|
+
|
|
101
|
+
remaining = seconds_until(resolved)
|
|
102
|
+
if not pending and not _missing(groups, collected):
|
|
103
|
+
break
|
|
104
|
+
if remaining <= risk_buffer or not pending:
|
|
105
|
+
for name in list(pending):
|
|
106
|
+
groups[name][0].cancel(pending.pop(name))
|
|
107
|
+
if fallback == "sync":
|
|
108
|
+
for j in _missing(groups, collected):
|
|
109
|
+
result = groups[_venue_of(j, groups)][0].run_sync(j)
|
|
110
|
+
collected[j.id] = result
|
|
111
|
+
fell_back.add(j.id)
|
|
112
|
+
break
|
|
113
|
+
time.sleep(
|
|
114
|
+
poll_interval
|
|
115
|
+
if poll_interval is not None
|
|
116
|
+
else min(30.0, max(2.0, remaining / 50.0))
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
completed_at = datetime.now().astimezone()
|
|
120
|
+
results: list[Result] = []
|
|
121
|
+
for j in job_list:
|
|
122
|
+
result = collected.get(j.id)
|
|
123
|
+
if result is None:
|
|
124
|
+
result = Result(job=j, error="not returned by venue before the deadline")
|
|
125
|
+
j.status = Status.FAILED
|
|
126
|
+
else:
|
|
127
|
+
result.job = j
|
|
128
|
+
j.status = (
|
|
129
|
+
Status.FELL_BACK
|
|
130
|
+
if j.id in fell_back
|
|
131
|
+
else (Status.SUCCEEDED if result.ok else Status.FAILED)
|
|
132
|
+
)
|
|
133
|
+
input_tokens, output_tokens = _usage_tokens(result.raw)
|
|
134
|
+
result.receipt = Receipt(
|
|
135
|
+
venue=groups[_venue_of(j, groups)][0].name,
|
|
136
|
+
model=j.model,
|
|
137
|
+
deadline=resolved,
|
|
138
|
+
submitted_at=submitted_at,
|
|
139
|
+
completed_at=completed_at if result.error is None else None,
|
|
140
|
+
input_tokens=input_tokens,
|
|
141
|
+
output_tokens=output_tokens,
|
|
142
|
+
fell_back=j.id in fell_back,
|
|
143
|
+
)
|
|
144
|
+
results.append(result)
|
|
145
|
+
return results
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _venue_of(j: Job, groups: dict[str, tuple[Venue, list[Job]]]) -> str:
|
|
149
|
+
for name, (_, group_jobs) in groups.items():
|
|
150
|
+
if j in group_jobs:
|
|
151
|
+
return name
|
|
152
|
+
raise KeyError(j.id)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _missing(
|
|
156
|
+
groups: dict[str, tuple[Venue, list[Job]]], collected: dict[str, Result]
|
|
157
|
+
) -> list[Job]:
|
|
158
|
+
return [j for _, (_, js) in groups.items() for j in js if j.id not in collected]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@dataclass
|
|
162
|
+
class Settlement:
|
|
163
|
+
"""Aggregate receipt across a run."""
|
|
164
|
+
|
|
165
|
+
total: int = 0
|
|
166
|
+
ok: int = 0
|
|
167
|
+
sla_met: int = 0
|
|
168
|
+
fell_back: int = 0
|
|
169
|
+
input_tokens: int = 0
|
|
170
|
+
output_tokens: int = 0
|
|
171
|
+
list_usd: float = 0.0
|
|
172
|
+
paid_usd: float = 0.0
|
|
173
|
+
unpriced: int = 0
|
|
174
|
+
by_venue: dict = field(default_factory=dict)
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def captured_usd(self) -> float:
|
|
178
|
+
return self.list_usd - self.paid_usd
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def captured_pct(self) -> float:
|
|
182
|
+
return 0.0 if not self.list_usd else 100.0 * self.captured_usd / self.list_usd
|
|
183
|
+
|
|
184
|
+
def __str__(self) -> str:
|
|
185
|
+
venues = " · ".join(f"{k} {v}" for k, v in sorted(self.by_venue.items()))
|
|
186
|
+
lines = [
|
|
187
|
+
"OFFPEAK SETTLEMENT " + "─" * 28,
|
|
188
|
+
f"jobs {self.total} ({self.ok} ok, {self.fell_back} sync fallback)",
|
|
189
|
+
f"sla {self.sla_met}/{self.total} met",
|
|
190
|
+
f"venues {venues or '—'}",
|
|
191
|
+
f"tokens {self.input_tokens:,} in · {self.output_tokens:,} out",
|
|
192
|
+
f"list ${self.list_usd:,.2f}",
|
|
193
|
+
f"paid ${self.paid_usd:,.2f}",
|
|
194
|
+
f"captured ${self.captured_usd:,.2f} ({self.captured_pct:.1f}%)",
|
|
195
|
+
f"prices snapshot {PRICE_SHEET_DATE} — override via offpeak.prices",
|
|
196
|
+
]
|
|
197
|
+
if self.unpriced:
|
|
198
|
+
lines.append(f"note {self.unpriced} job(s) had no price sheet entry")
|
|
199
|
+
lines.append("─" * 47)
|
|
200
|
+
return "\n".join(lines)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def receipt(results: list[Result]) -> Settlement:
|
|
204
|
+
"""Settle a run: aggregate per-job receipts into one :class:`Settlement`."""
|
|
205
|
+
settlement = Settlement()
|
|
206
|
+
for result in results:
|
|
207
|
+
settlement.total += 1
|
|
208
|
+
if result.ok:
|
|
209
|
+
settlement.ok += 1
|
|
210
|
+
r = result.receipt
|
|
211
|
+
if r is None:
|
|
212
|
+
continue
|
|
213
|
+
settlement.sla_met += int(r.sla_met)
|
|
214
|
+
settlement.fell_back += int(r.fell_back)
|
|
215
|
+
settlement.input_tokens += r.input_tokens
|
|
216
|
+
settlement.output_tokens += r.output_tokens
|
|
217
|
+
settlement.by_venue[r.venue] = settlement.by_venue.get(r.venue, 0) + 1
|
|
218
|
+
if r.list_usd is None or r.paid_usd is None:
|
|
219
|
+
settlement.unpriced += 1
|
|
220
|
+
else:
|
|
221
|
+
settlement.list_usd += r.list_usd
|
|
222
|
+
settlement.paid_usd += r.paid_usd
|
|
223
|
+
return settlement
|
offpeak/deadline.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Deadline parsing — how software says "this can wait".
|
|
2
|
+
|
|
3
|
+
Accepted forms:
|
|
4
|
+
|
|
5
|
+
- ``datetime`` — aware or naive; a naive datetime is assumed to be local time.
|
|
6
|
+
- ``timedelta`` — relative to now.
|
|
7
|
+
- ``int`` / ``float`` — seconds from now.
|
|
8
|
+
- ``"06:00"`` — the next occurrence of that wall-clock time (today if it is
|
|
9
|
+
still ahead, otherwise tomorrow). This is the canonical overnight form.
|
|
10
|
+
- ``"6h"``, ``"90m"``, ``"45s"``, ``"2d"`` — relative to now.
|
|
11
|
+
- ISO 8601 strings — ``"2026-08-21T06:00:00-07:00"``.
|
|
12
|
+
|
|
13
|
+
All deadlines resolve to an aware :class:`datetime.datetime`. See SPEC.md for
|
|
14
|
+
the full semantics.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from datetime import datetime, timedelta
|
|
21
|
+
|
|
22
|
+
__all__ = ["parse_deadline", "seconds_until"]
|
|
23
|
+
|
|
24
|
+
_REL = re.compile(
|
|
25
|
+
r"^\s*(\d+(?:\.\d+)?)\s*(s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?|d|days?)\s*$",
|
|
26
|
+
re.IGNORECASE,
|
|
27
|
+
)
|
|
28
|
+
_WALL = re.compile(r"^\s*([01]?\d|2[0-3]):([0-5]\d)\s*$")
|
|
29
|
+
_UNIT_SECONDS = {"s": 1.0, "m": 60.0, "h": 3600.0, "d": 86400.0}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _local_now() -> datetime:
|
|
33
|
+
return datetime.now().astimezone()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def parse_deadline(value: object, *, now: datetime | None = None) -> datetime:
|
|
37
|
+
"""Resolve *value* to an aware datetime.
|
|
38
|
+
|
|
39
|
+
Raises ``ValueError`` if the form is unrecognized or the resolved deadline
|
|
40
|
+
is not in the future, and ``TypeError`` for unsupported types.
|
|
41
|
+
"""
|
|
42
|
+
if now is None:
|
|
43
|
+
now = _local_now()
|
|
44
|
+
elif now.tzinfo is None:
|
|
45
|
+
now = now.astimezone()
|
|
46
|
+
deadline = _parse(value, now)
|
|
47
|
+
if deadline <= now:
|
|
48
|
+
raise ValueError(
|
|
49
|
+
f"deadline {deadline.isoformat()} is not in the future (now: {now.isoformat()})"
|
|
50
|
+
)
|
|
51
|
+
return deadline
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def seconds_until(deadline: datetime, *, now: datetime | None = None) -> float:
|
|
55
|
+
"""Seconds remaining until *deadline* (negative if it has passed)."""
|
|
56
|
+
if now is None:
|
|
57
|
+
now = _local_now()
|
|
58
|
+
return (deadline - now).total_seconds()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _parse(value: object, now: datetime) -> datetime:
|
|
62
|
+
if isinstance(value, datetime):
|
|
63
|
+
return value if value.tzinfo else value.astimezone()
|
|
64
|
+
if isinstance(value, timedelta):
|
|
65
|
+
return now + value
|
|
66
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
67
|
+
return now + timedelta(seconds=float(value))
|
|
68
|
+
if isinstance(value, str):
|
|
69
|
+
if m := _REL.match(value):
|
|
70
|
+
qty = float(m.group(1))
|
|
71
|
+
unit = m.group(2)[0].lower()
|
|
72
|
+
return now + timedelta(seconds=qty * _UNIT_SECONDS[unit])
|
|
73
|
+
if m := _WALL.match(value):
|
|
74
|
+
hour, minute = int(m.group(1)), int(m.group(2))
|
|
75
|
+
candidate = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
|
76
|
+
if candidate <= now:
|
|
77
|
+
candidate += timedelta(days=1)
|
|
78
|
+
return candidate
|
|
79
|
+
try:
|
|
80
|
+
parsed = datetime.fromisoformat(value.strip())
|
|
81
|
+
except ValueError:
|
|
82
|
+
raise ValueError(f"unrecognized deadline: {value!r}") from None
|
|
83
|
+
return parsed if parsed.tzinfo else parsed.astimezone()
|
|
84
|
+
raise TypeError(f"unsupported deadline type: {type(value).__name__}")
|
offpeak/job.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Job, Result, and Receipt — the unit of deferred work and its settlement."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from enum import Enum
|
|
9
|
+
|
|
10
|
+
from .prices import batch_cost_usd, list_cost_usd
|
|
11
|
+
|
|
12
|
+
__all__ = ["Job", "Result", "Receipt", "Status", "job"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Status(str, Enum):
|
|
16
|
+
QUEUED = "queued"
|
|
17
|
+
SUBMITTED = "submitted"
|
|
18
|
+
SUCCEEDED = "succeeded"
|
|
19
|
+
FAILED = "failed"
|
|
20
|
+
FELL_BACK = "fell_back" # completed, but via the sync fallback (list price)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Job:
|
|
25
|
+
"""A venue-agnostic chat-completion job."""
|
|
26
|
+
|
|
27
|
+
model: str
|
|
28
|
+
messages: list[dict]
|
|
29
|
+
params: dict = field(default_factory=dict)
|
|
30
|
+
id: str = field(default_factory=lambda: f"job_{uuid.uuid4().hex[:12]}")
|
|
31
|
+
metadata: dict = field(default_factory=dict)
|
|
32
|
+
status: Status = Status.QUEUED
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def job(
|
|
36
|
+
model: str,
|
|
37
|
+
input: str | list[dict] | None = None,
|
|
38
|
+
*,
|
|
39
|
+
system: str | None = None,
|
|
40
|
+
metadata: dict | None = None,
|
|
41
|
+
**params: object,
|
|
42
|
+
) -> Job:
|
|
43
|
+
"""Build a :class:`Job`.
|
|
44
|
+
|
|
45
|
+
``input`` may be a plain prompt string or a full ``messages`` list.
|
|
46
|
+
Extra keyword arguments (``temperature``, ``max_tokens``, ...) are passed
|
|
47
|
+
through to the venue.
|
|
48
|
+
"""
|
|
49
|
+
if input is None:
|
|
50
|
+
raise ValueError("job() requires an input (a prompt string or a messages list)")
|
|
51
|
+
if isinstance(input, str):
|
|
52
|
+
messages = [{"role": "user", "content": input}]
|
|
53
|
+
else:
|
|
54
|
+
messages = list(input)
|
|
55
|
+
if system is not None:
|
|
56
|
+
messages = [{"role": "system", "content": system}, *messages]
|
|
57
|
+
return Job(model=model, messages=messages, params=dict(params), metadata=metadata or {})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class Receipt:
|
|
62
|
+
"""Per-job settlement: what ran where, when, and what the hour was worth."""
|
|
63
|
+
|
|
64
|
+
venue: str
|
|
65
|
+
model: str
|
|
66
|
+
deadline: datetime
|
|
67
|
+
submitted_at: datetime
|
|
68
|
+
completed_at: datetime | None = None
|
|
69
|
+
input_tokens: int = 0
|
|
70
|
+
output_tokens: int = 0
|
|
71
|
+
fell_back: bool = False
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def sla_met(self) -> bool:
|
|
75
|
+
return self.completed_at is not None and self.completed_at <= self.deadline
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def list_usd(self) -> float | None:
|
|
79
|
+
"""What the job would have cost run synchronously at list price."""
|
|
80
|
+
return list_cost_usd(self.model, self.input_tokens, self.output_tokens)
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def paid_usd(self) -> float | None:
|
|
84
|
+
"""What the job cost on the venue it actually ran on."""
|
|
85
|
+
if self.fell_back:
|
|
86
|
+
return self.list_usd
|
|
87
|
+
return batch_cost_usd(self.model, self.input_tokens, self.output_tokens)
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def spread_usd(self) -> float | None:
|
|
91
|
+
"""Captured spread: list minus paid."""
|
|
92
|
+
if self.list_usd is None or self.paid_usd is None:
|
|
93
|
+
return None
|
|
94
|
+
return self.list_usd - self.paid_usd
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class Result:
|
|
99
|
+
"""The outcome of one job."""
|
|
100
|
+
|
|
101
|
+
job: Job
|
|
102
|
+
text: str | None = None
|
|
103
|
+
raw: object = None
|
|
104
|
+
error: str | None = None
|
|
105
|
+
receipt: Receipt | None = None
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def ok(self) -> bool:
|
|
109
|
+
return self.error is None and self.text is not None
|
offpeak/prices.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""List-price sheet and batch discounts, for receipts.
|
|
2
|
+
|
|
3
|
+
Receipts are arithmetic against public price sheets — no estimates. The prices
|
|
4
|
+
below are a **bundled snapshot** (see ``PRICE_SHEET_DATE``); providers change
|
|
5
|
+
prices, so verify against their published sheets and override at runtime with
|
|
6
|
+
:func:`register_price` where they have moved. Costs for unknown models resolve
|
|
7
|
+
to ``None`` rather than a guess.
|
|
8
|
+
|
|
9
|
+
Batch tiers at OpenAI, Anthropic, and Google are publicly priced at 50% of
|
|
10
|
+
list, which is what :data:`BATCH_DISCOUNT` encodes.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"PRICE_SHEET_DATE",
|
|
17
|
+
"BATCH_DISCOUNT",
|
|
18
|
+
"register_price",
|
|
19
|
+
"get_price",
|
|
20
|
+
"list_cost_usd",
|
|
21
|
+
"batch_cost_usd",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
PRICE_SHEET_DATE = "2026-08"
|
|
25
|
+
|
|
26
|
+
# Fraction of list price paid on provider batch tiers (published: 50%).
|
|
27
|
+
BATCH_DISCOUNT = 0.5
|
|
28
|
+
|
|
29
|
+
# model -> (USD per 1M input tokens, USD per 1M output tokens), standard list.
|
|
30
|
+
_PRICES: dict[str, tuple[float, float]] = {
|
|
31
|
+
# Anthropic (per anthropic.com/pricing)
|
|
32
|
+
"claude-opus-4-5": (5.00, 25.00),
|
|
33
|
+
"claude-sonnet-4-5": (3.00, 15.00),
|
|
34
|
+
"claude-haiku-4-5": (1.00, 5.00),
|
|
35
|
+
# OpenAI (per openai.com/api/pricing)
|
|
36
|
+
"gpt-5.1": (1.25, 10.00),
|
|
37
|
+
"gpt-5.1-mini": (0.25, 2.00),
|
|
38
|
+
"gpt-5.1-nano": (0.05, 0.40),
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def register_price(model: str, input_per_m: float, output_per_m: float) -> None:
|
|
43
|
+
"""Set or override the list price for *model* (USD per 1M tokens)."""
|
|
44
|
+
_PRICES[model] = (float(input_per_m), float(output_per_m))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def get_price(model: str) -> tuple[float, float] | None:
|
|
48
|
+
"""Exact match first, then longest registered prefix (handles date-pinned
|
|
49
|
+
model names like ``claude-sonnet-4-5-20250929``)."""
|
|
50
|
+
if model in _PRICES:
|
|
51
|
+
return _PRICES[model]
|
|
52
|
+
best = None
|
|
53
|
+
for name, price in _PRICES.items():
|
|
54
|
+
if model.startswith(name) and (best is None or len(name) > best[0]):
|
|
55
|
+
best = (len(name), price)
|
|
56
|
+
return best[1] if best else None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def list_cost_usd(model: str, input_tokens: int, output_tokens: int) -> float | None:
|
|
60
|
+
price = get_price(model)
|
|
61
|
+
if price is None:
|
|
62
|
+
return None
|
|
63
|
+
return (input_tokens * price[0] + output_tokens * price[1]) / 1_000_000
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def batch_cost_usd(model: str, input_tokens: int, output_tokens: int) -> float | None:
|
|
67
|
+
cost = list_cost_usd(model, input_tokens, output_tokens)
|
|
68
|
+
return None if cost is None else cost * BATCH_DISCOUNT
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Anthropic Message Batches venue (−50% vs list, 24h completion window).
|
|
2
|
+
|
|
3
|
+
Uses your own ``ANTHROPIC_API_KEY``. Requires the ``anthropic`` extra:
|
|
4
|
+
``pip install "offpeak[anthropic]"``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from ..job import Job, Result
|
|
10
|
+
from .base import BatchState, Venue
|
|
11
|
+
|
|
12
|
+
__all__ = ["AnthropicBatch", "build_requests"]
|
|
13
|
+
|
|
14
|
+
_DEFAULT_MAX_TOKENS = 4096
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def build_requests(jobs: list[Job]) -> list[dict]:
|
|
18
|
+
"""Render *jobs* as Message Batches request dicts."""
|
|
19
|
+
requests = []
|
|
20
|
+
for j in jobs:
|
|
21
|
+
system = None
|
|
22
|
+
messages = []
|
|
23
|
+
for message in j.messages:
|
|
24
|
+
if message.get("role") == "system":
|
|
25
|
+
system = message.get("content")
|
|
26
|
+
else:
|
|
27
|
+
messages.append(message)
|
|
28
|
+
params = {
|
|
29
|
+
"model": j.model,
|
|
30
|
+
"messages": messages,
|
|
31
|
+
"max_tokens": j.params.get("max_tokens", _DEFAULT_MAX_TOKENS),
|
|
32
|
+
**{k: v for k, v in j.params.items() if k != "max_tokens"},
|
|
33
|
+
}
|
|
34
|
+
if system is not None:
|
|
35
|
+
params["system"] = system
|
|
36
|
+
requests.append({"custom_id": j.id, "params": params})
|
|
37
|
+
return requests
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _text_of(message: object) -> str:
|
|
41
|
+
blocks = getattr(message, "content", None) or []
|
|
42
|
+
parts = []
|
|
43
|
+
for block in blocks:
|
|
44
|
+
text = getattr(block, "text", None)
|
|
45
|
+
if text is None and isinstance(block, dict):
|
|
46
|
+
text = block.get("text")
|
|
47
|
+
if text:
|
|
48
|
+
parts.append(text)
|
|
49
|
+
return "".join(parts)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class AnthropicBatch(Venue):
|
|
53
|
+
name = "anthropic:batch"
|
|
54
|
+
|
|
55
|
+
def __init__(self, client: object | None = None):
|
|
56
|
+
self._client = client
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def client(self):
|
|
60
|
+
if self._client is None:
|
|
61
|
+
try:
|
|
62
|
+
from anthropic import Anthropic
|
|
63
|
+
except ImportError as exc: # pragma: no cover
|
|
64
|
+
raise ImportError(
|
|
65
|
+
'Anthropic venue requires the anthropic SDK: pip install "offpeak[anthropic]"'
|
|
66
|
+
) from exc
|
|
67
|
+
self._client = Anthropic()
|
|
68
|
+
return self._client
|
|
69
|
+
|
|
70
|
+
def supports(self, model: str) -> bool:
|
|
71
|
+
return model.startswith("claude")
|
|
72
|
+
|
|
73
|
+
def submit(self, jobs: list[Job]) -> str:
|
|
74
|
+
batch = self.client.messages.batches.create(requests=build_requests(jobs))
|
|
75
|
+
return batch.id
|
|
76
|
+
|
|
77
|
+
def status(self, handle: str) -> BatchState:
|
|
78
|
+
batch = self.client.messages.batches.retrieve(handle)
|
|
79
|
+
counts = getattr(batch, "request_counts", None)
|
|
80
|
+
processing = getattr(batch, "processing_status", "in_progress")
|
|
81
|
+
status = "completed" if processing == "ended" else "in_progress"
|
|
82
|
+
if processing in ("canceling", "cancelled"):
|
|
83
|
+
status = "cancelled"
|
|
84
|
+
return BatchState(
|
|
85
|
+
status=status,
|
|
86
|
+
completed=getattr(counts, "succeeded", 0) or 0,
|
|
87
|
+
failed=(getattr(counts, "errored", 0) or 0) + (getattr(counts, "expired", 0) or 0),
|
|
88
|
+
total=sum(
|
|
89
|
+
getattr(counts, k, 0) or 0
|
|
90
|
+
for k in ("processing", "succeeded", "errored", "canceled", "expired")
|
|
91
|
+
),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def collect(self, handle: str) -> dict[str, Result]:
|
|
95
|
+
results: dict[str, Result] = {}
|
|
96
|
+
for entry in self.client.messages.batches.results(handle):
|
|
97
|
+
outcome = entry.result
|
|
98
|
+
if getattr(outcome, "type", None) == "succeeded":
|
|
99
|
+
message = outcome.message
|
|
100
|
+
usage = getattr(message, "usage", None)
|
|
101
|
+
results[entry.custom_id] = Result(
|
|
102
|
+
job=None,
|
|
103
|
+
text=_text_of(message),
|
|
104
|
+
raw={
|
|
105
|
+
"input_tokens": getattr(usage, "input_tokens", 0),
|
|
106
|
+
"output_tokens": getattr(usage, "output_tokens", 0),
|
|
107
|
+
},
|
|
108
|
+
)
|
|
109
|
+
else:
|
|
110
|
+
results[entry.custom_id] = Result(
|
|
111
|
+
job=None, error=f"{getattr(outcome, 'type', 'error')}: {outcome}"
|
|
112
|
+
)
|
|
113
|
+
return results
|
|
114
|
+
|
|
115
|
+
def cancel(self, handle: str) -> None:
|
|
116
|
+
try:
|
|
117
|
+
self.client.messages.batches.cancel(handle)
|
|
118
|
+
except Exception: # noqa: BLE001 — best-effort
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
def run_sync(self, job: Job) -> Result:
|
|
122
|
+
requests = build_requests([job])
|
|
123
|
+
params = requests[0]["params"]
|
|
124
|
+
try:
|
|
125
|
+
message = self.client.messages.create(**params)
|
|
126
|
+
except Exception as exc: # noqa: BLE001
|
|
127
|
+
return Result(job=job, error=str(exc))
|
|
128
|
+
usage = getattr(message, "usage", None)
|
|
129
|
+
return Result(
|
|
130
|
+
job=job,
|
|
131
|
+
text=_text_of(message),
|
|
132
|
+
raw={
|
|
133
|
+
"input_tokens": getattr(usage, "input_tokens", 0),
|
|
134
|
+
"output_tokens": getattr(usage, "output_tokens", 0),
|
|
135
|
+
},
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def usage_tokens(usage: dict) -> tuple[int, int]:
|
|
140
|
+
"""(input_tokens, output_tokens) from an Anthropic usage dict."""
|
|
141
|
+
return int(usage.get("input_tokens", 0) or 0), int(usage.get("output_tokens", 0) or 0)
|
offpeak/venues/base.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""The Venue interface — anywhere a deferred job can run.
|
|
2
|
+
|
|
3
|
+
v0.1 ships provider batch tiers. The same interface is how off-peak windows on
|
|
4
|
+
your own GPUs, spot capacity, and cleaner regions plug in later.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from abc import ABC, abstractmethod
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from ..job import Job, Result
|
|
13
|
+
|
|
14
|
+
__all__ = ["Venue", "BatchState"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class BatchState:
|
|
19
|
+
"""A venue batch's progress."""
|
|
20
|
+
|
|
21
|
+
status: str # "in_progress" | "completed" | "failed" | "cancelled"
|
|
22
|
+
completed: int = 0
|
|
23
|
+
failed: int = 0
|
|
24
|
+
total: int = 0
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def done(self) -> bool:
|
|
28
|
+
return self.status in ("completed", "failed", "cancelled")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Venue(ABC):
|
|
32
|
+
"""A place deferred work can execute, plus a synchronous escape hatch."""
|
|
33
|
+
|
|
34
|
+
name: str = "venue"
|
|
35
|
+
|
|
36
|
+
@abstractmethod
|
|
37
|
+
def supports(self, model: str) -> bool:
|
|
38
|
+
"""Whether this venue can run *model*."""
|
|
39
|
+
|
|
40
|
+
@abstractmethod
|
|
41
|
+
def submit(self, jobs: list[Job]) -> str:
|
|
42
|
+
"""Submit *jobs* as one batch; return an opaque batch handle."""
|
|
43
|
+
|
|
44
|
+
@abstractmethod
|
|
45
|
+
def status(self, handle: str) -> BatchState:
|
|
46
|
+
"""Poll a batch's progress."""
|
|
47
|
+
|
|
48
|
+
@abstractmethod
|
|
49
|
+
def collect(self, handle: str) -> dict[str, Result]:
|
|
50
|
+
"""Fetch results for a finished batch, keyed by job id."""
|
|
51
|
+
|
|
52
|
+
@abstractmethod
|
|
53
|
+
def cancel(self, handle: str) -> None:
|
|
54
|
+
"""Best-effort cancel of an in-flight batch."""
|
|
55
|
+
|
|
56
|
+
@abstractmethod
|
|
57
|
+
def run_sync(self, job: Job) -> Result:
|
|
58
|
+
"""Run one job synchronously at list price (the SLA fallback path)."""
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""OpenAI Batch API venue (−50% vs list, 24h completion window).
|
|
2
|
+
|
|
3
|
+
Uses your own ``OPENAI_API_KEY``. Requires the ``openai`` extra:
|
|
4
|
+
``pip install "offpeak[openai]"``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
from ..job import Job, Result
|
|
12
|
+
from .base import BatchState, Venue
|
|
13
|
+
|
|
14
|
+
__all__ = ["OpenAIBatch", "build_jsonl", "parse_output_line"]
|
|
15
|
+
|
|
16
|
+
_MODEL_PREFIXES = ("gpt-", "o1", "o3", "o4", "chatgpt-")
|
|
17
|
+
_ENDPOINT = "/v1/chat/completions"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def build_jsonl(jobs: list[Job]) -> bytes:
|
|
21
|
+
"""Render *jobs* as OpenAI Batch API JSONL (one request per line)."""
|
|
22
|
+
lines = []
|
|
23
|
+
for j in jobs:
|
|
24
|
+
body = {"model": j.model, "messages": j.messages, **j.params}
|
|
25
|
+
lines.append(
|
|
26
|
+
json.dumps(
|
|
27
|
+
{"custom_id": j.id, "method": "POST", "url": _ENDPOINT, "body": body},
|
|
28
|
+
ensure_ascii=False,
|
|
29
|
+
)
|
|
30
|
+
)
|
|
31
|
+
return ("\n".join(lines) + "\n").encode("utf-8")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def parse_output_line(line: str) -> tuple[str, str | None, dict, str | None]:
|
|
35
|
+
"""Parse one output-file line -> (job_id, text, usage, error)."""
|
|
36
|
+
record = json.loads(line)
|
|
37
|
+
job_id = record.get("custom_id", "")
|
|
38
|
+
if record.get("error"):
|
|
39
|
+
return job_id, None, {}, str(record["error"])
|
|
40
|
+
response = record.get("response") or {}
|
|
41
|
+
body = response.get("body") or {}
|
|
42
|
+
if response.get("status_code") not in (200, None):
|
|
43
|
+
return job_id, None, {}, f"HTTP {response.get('status_code')}: {body}"
|
|
44
|
+
try:
|
|
45
|
+
text = body["choices"][0]["message"]["content"]
|
|
46
|
+
except (KeyError, IndexError, TypeError):
|
|
47
|
+
return job_id, None, {}, f"unexpected response body: {body!r}"
|
|
48
|
+
return job_id, text, body.get("usage") or {}, None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class OpenAIBatch(Venue):
|
|
52
|
+
name = "openai:batch"
|
|
53
|
+
|
|
54
|
+
def __init__(self, client: object | None = None):
|
|
55
|
+
self._client = client
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def client(self):
|
|
59
|
+
if self._client is None:
|
|
60
|
+
try:
|
|
61
|
+
from openai import OpenAI
|
|
62
|
+
except ImportError as exc: # pragma: no cover
|
|
63
|
+
raise ImportError(
|
|
64
|
+
'OpenAI venue requires the openai SDK: pip install "offpeak[openai]"'
|
|
65
|
+
) from exc
|
|
66
|
+
self._client = OpenAI()
|
|
67
|
+
return self._client
|
|
68
|
+
|
|
69
|
+
def supports(self, model: str) -> bool:
|
|
70
|
+
return model.startswith(_MODEL_PREFIXES)
|
|
71
|
+
|
|
72
|
+
def submit(self, jobs: list[Job]) -> str:
|
|
73
|
+
upload = self.client.files.create(
|
|
74
|
+
file=("offpeak_batch.jsonl", build_jsonl(jobs)), purpose="batch"
|
|
75
|
+
)
|
|
76
|
+
batch = self.client.batches.create(
|
|
77
|
+
input_file_id=upload.id, endpoint=_ENDPOINT, completion_window="24h"
|
|
78
|
+
)
|
|
79
|
+
return batch.id
|
|
80
|
+
|
|
81
|
+
def status(self, handle: str) -> BatchState:
|
|
82
|
+
batch = self.client.batches.retrieve(handle)
|
|
83
|
+
mapping = {
|
|
84
|
+
"validating": "in_progress",
|
|
85
|
+
"in_progress": "in_progress",
|
|
86
|
+
"finalizing": "in_progress",
|
|
87
|
+
"completed": "completed",
|
|
88
|
+
"failed": "failed",
|
|
89
|
+
"expired": "failed",
|
|
90
|
+
"cancelling": "cancelled",
|
|
91
|
+
"cancelled": "cancelled",
|
|
92
|
+
}
|
|
93
|
+
counts = getattr(batch, "request_counts", None)
|
|
94
|
+
return BatchState(
|
|
95
|
+
status=mapping.get(batch.status, "in_progress"),
|
|
96
|
+
completed=getattr(counts, "completed", 0) or 0,
|
|
97
|
+
failed=getattr(counts, "failed", 0) or 0,
|
|
98
|
+
total=getattr(counts, "total", 0) or 0,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def collect(self, handle: str) -> dict[str, Result]:
|
|
102
|
+
batch = self.client.batches.retrieve(handle)
|
|
103
|
+
out: dict[str, tuple[str | None, dict, str | None]] = {}
|
|
104
|
+
for file_id in (batch.output_file_id, batch.error_file_id):
|
|
105
|
+
if not file_id:
|
|
106
|
+
continue
|
|
107
|
+
content = self.client.files.content(file_id).text
|
|
108
|
+
for line in content.splitlines():
|
|
109
|
+
if not line.strip():
|
|
110
|
+
continue
|
|
111
|
+
job_id, text, usage, error = parse_output_line(line)
|
|
112
|
+
out[job_id] = (text, usage, error)
|
|
113
|
+
results: dict[str, Result] = {}
|
|
114
|
+
for job_id, (text, usage, error) in out.items():
|
|
115
|
+
results[job_id] = Result(
|
|
116
|
+
job=None, # attached by the scheduler
|
|
117
|
+
text=text,
|
|
118
|
+
raw=usage,
|
|
119
|
+
error=error,
|
|
120
|
+
)
|
|
121
|
+
return results
|
|
122
|
+
|
|
123
|
+
def cancel(self, handle: str) -> None:
|
|
124
|
+
try:
|
|
125
|
+
self.client.batches.cancel(handle)
|
|
126
|
+
except Exception: # noqa: BLE001 — best-effort
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
def run_sync(self, job: Job) -> Result:
|
|
130
|
+
try:
|
|
131
|
+
response = self.client.chat.completions.create(
|
|
132
|
+
model=job.model, messages=job.messages, **job.params
|
|
133
|
+
)
|
|
134
|
+
except Exception as exc: # noqa: BLE001
|
|
135
|
+
return Result(job=job, error=str(exc))
|
|
136
|
+
usage = getattr(response, "usage", None)
|
|
137
|
+
return Result(
|
|
138
|
+
job=job,
|
|
139
|
+
text=response.choices[0].message.content,
|
|
140
|
+
raw={
|
|
141
|
+
"prompt_tokens": getattr(usage, "prompt_tokens", 0),
|
|
142
|
+
"completion_tokens": getattr(usage, "completion_tokens", 0),
|
|
143
|
+
},
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def usage_tokens(usage: dict) -> tuple[int, int]:
|
|
148
|
+
"""(input_tokens, output_tokens) from an OpenAI usage dict."""
|
|
149
|
+
return int(usage.get("prompt_tokens", 0) or 0), int(usage.get("completion_tokens", 0) or 0)
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: offpeak
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deadline-priced inference: give AI jobs a deadline and run them on the cheapest venue — provider batch tiers (−50%) today. Same model, same tokens, a different hour.
|
|
5
|
+
Project-URL: Homepage, https://github.com/offpeak-ai/offpeak
|
|
6
|
+
Project-URL: Repository, https://github.com/offpeak-ai/offpeak
|
|
7
|
+
Project-URL: Issues, https://github.com/offpeak-ai/offpeak/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/offpeak-ai/offpeak/releases
|
|
9
|
+
Author: Offpeak
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: anthropic,batch,batch-api,cost-optimization,deadline,finops,inference,llm,openai,scheduling
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Provides-Extra: all
|
|
25
|
+
Requires-Dist: anthropic>=0.40; extra == 'all'
|
|
26
|
+
Requires-Dist: openai>=1.50; extra == 'all'
|
|
27
|
+
Provides-Extra: anthropic
|
|
28
|
+
Requires-Dist: anthropic>=0.40; extra == 'anthropic'
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: build; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
32
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
33
|
+
Requires-Dist: twine; extra == 'dev'
|
|
34
|
+
Provides-Extra: openai
|
|
35
|
+
Requires-Dist: openai>=1.50; extra == 'openai'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# offpeak
|
|
39
|
+
|
|
40
|
+
**Deadline-priced inference.** Same model, same tokens, a different hour — for half the price.
|
|
41
|
+
|
|
42
|
+
[](https://github.com/offpeak-ai/offpeak/actions/workflows/ci.yml)
|
|
43
|
+
[](https://pypi.org/project/offpeak/)
|
|
44
|
+
[](LICENSE)
|
|
45
|
+
|
|
46
|
+
OpenAI, Anthropic, and Google all sell batch inference at **50% off list price**. Almost nobody uses it, because no API lets work say it can wait: every token runs "now" by default, and the batch workflow — build a file, upload, poll, download, match results back up — is enough friction that urgency gets bought by accident.
|
|
47
|
+
|
|
48
|
+
`offpeak` gives your code one new argument.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import offpeak
|
|
52
|
+
|
|
53
|
+
jobs = [offpeak.job("claude-haiku-4-5", f"Summarize:\n\n{doc}") for doc in docs]
|
|
54
|
+
|
|
55
|
+
results = offpeak.run(jobs, deadline="06:00") # done by 6am, at batch prices
|
|
56
|
+
|
|
57
|
+
print(offpeak.receipt(results))
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
OFFPEAK SETTLEMENT ────────────────────────────
|
|
62
|
+
jobs 1,000 (1,000 ok, 2 sync fallback)
|
|
63
|
+
sla 1,000/1,000 met
|
|
64
|
+
venues anthropic:batch 1,000
|
|
65
|
+
tokens 12,410,332 in · 3,104,551 out
|
|
66
|
+
list $27.93
|
|
67
|
+
paid $14.02
|
|
68
|
+
captured $13.91 (49.8%)
|
|
69
|
+
prices snapshot 2026-08 — override via offpeak.prices
|
|
70
|
+
───────────────────────────────────────────────
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## What it does
|
|
74
|
+
|
|
75
|
+
- **One argument, not a workflow.** `run(jobs, deadline=...)` handles batching, submission, polling, collection, and result matching across providers.
|
|
76
|
+
- **Deadlines are guarded, not hoped for.** If a batch hasn't landed by the time the remaining window shrinks to a risk buffer, `offpeak` cancels and re-runs the stragglers synchronously at list price. You state the deadline; it gets met.
|
|
77
|
+
- **Every run settles a receipt.** List cost, paid cost, captured spread — arithmetic against public price sheets, not estimates.
|
|
78
|
+
- **Your keys, your perimeter.** `offpeak` talks directly to the providers with your own API keys. There is no proxy and no third party in the data path.
|
|
79
|
+
- **Zero-dependency core.** Provider SDKs load only via extras.
|
|
80
|
+
|
|
81
|
+
## Install
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
pip install "offpeak[all]" # OpenAI + Anthropic venues
|
|
85
|
+
pip install "offpeak[anthropic]" # or one provider
|
|
86
|
+
pip install "offpeak[openai]"
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Venues use the standard environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`), or pass a configured client: `OpenAIBatch(client=my_client)`.
|
|
90
|
+
|
|
91
|
+
## Deadlines
|
|
92
|
+
|
|
93
|
+
Deadlines are how software says "this can wait" — the full semantics live in [SPEC.md](SPEC.md).
|
|
94
|
+
|
|
95
|
+
| Form | Meaning |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| `"06:00"` | the next 6am, local time (the canonical overnight form) |
|
|
98
|
+
| `"4h"`, `"90m"`, `"2d"` | relative to now |
|
|
99
|
+
| `"2026-08-21T06:00:00-07:00"` | ISO 8601, absolute |
|
|
100
|
+
| `datetime` / `timedelta` / seconds | native Python forms |
|
|
101
|
+
|
|
102
|
+
## How a run works
|
|
103
|
+
|
|
104
|
+
1. Jobs are grouped by venue (`claude-*` → Anthropic Message Batches, `gpt-*`/`o*` → OpenAI Batch) and submitted at the batch tier — 50% of list.
|
|
105
|
+
2. `offpeak` polls the venues, backing off while the window is long.
|
|
106
|
+
3. When remaining time reaches the **risk buffer** (default: 15% of the window, clamped to 1–10 minutes), unfinished jobs are cancelled and re-run synchronously so the deadline holds. Set `fallback="none"` to report them instead.
|
|
107
|
+
4. Results come back in input order, each with a per-job `Receipt`; `offpeak.receipt(results)` settles the run.
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
results = offpeak.run(
|
|
111
|
+
jobs,
|
|
112
|
+
deadline="06:00",
|
|
113
|
+
fallback="sync", # meet the deadline at list price if the batch is at risk
|
|
114
|
+
risk_buffer=600, # seconds held in reserve (optional)
|
|
115
|
+
)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Receipts and prices
|
|
119
|
+
|
|
120
|
+
Receipts are computed against a bundled snapshot of public list prices (batch = 50% of list, as published). Providers change prices — verify and override at runtime:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
import offpeak
|
|
124
|
+
|
|
125
|
+
offpeak.prices.register_price("my-fine-tune", input_per_m=4.0, output_per_m=16.0)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Unknown models settle with `cost = None` rather than a guess.
|
|
129
|
+
|
|
130
|
+
## What this is (and the roadmap)
|
|
131
|
+
|
|
132
|
+
`offpeak` is the open client and spec for a simple claim: **intelligence has a time value**. A large share of AI work — embeddings, evals, backfills, report generation, overnight agents — has no human waiting on it, and the venues already price that patience at −50%. This library is the missing workflow.
|
|
133
|
+
|
|
134
|
+
The roadmap follows the same interface upward: more venues (Google batch, spot capacity, off-peak windows on your own GPUs), queue-latency forecasting instead of a fixed risk buffer, portfolio placement across venues, energy- and carbon-aware scheduling with per-job receipts. The venue interface (`offpeak.Venue`) is deliberately the extension point — a venue is anywhere deferred work can run.
|
|
135
|
+
|
|
136
|
+
A hosted desk that does the forecasting, cross-venue portfolio scheduling, and SLA insurance at fleet scale — payloads never leaving your perimeter — is being built by the same team. The SDK and the deadline spec stay open, Apache-2.0.
|
|
137
|
+
|
|
138
|
+
## Contributing
|
|
139
|
+
|
|
140
|
+
Issues and PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Spec changes start as issues against [SPEC.md](SPEC.md).
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
Apache-2.0 © Offpeak
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
offpeak/__init__.py,sha256=c162EB9ueM1zTqsKiSSNKZo4fWuyimm6Wj19Wa3vMiY,902
|
|
2
|
+
offpeak/client.py,sha256=8z-cShoDYNfaSV1zShktZGYHOYsR7F3ZOJVACwGGzk8,8060
|
|
3
|
+
offpeak/deadline.py,sha256=iA_Y3KnnAO93Gq1EzlUnKSnPMwu-XWiVSu9eTe5W9nU,3078
|
|
4
|
+
offpeak/job.py,sha256=0xDcsBVLBcQstufnq6lWnuMTVJx8n-UKXa9udabHqfk,3114
|
|
5
|
+
offpeak/prices.py,sha256=8aS-eV_J8oieDkW-xPESSHCOhpnC7g5lFxPwEQDYKBw,2387
|
|
6
|
+
offpeak/venues/__init__.py,sha256=O7JP5ZLneZuzWDaAoGtOSBHFLWM0sI928IxbZx_CLZ0,123
|
|
7
|
+
offpeak/venues/anthropic_batch.py,sha256=Tbwm-sWVEjL7ehLDDGa9Hge-rF6rchM9Ppm3JIs-Vbo,4985
|
|
8
|
+
offpeak/venues/base.py,sha256=6E5jQCueES1pdey9jf5ECkwxPfDnC5oju53ZV97fxQ8,1590
|
|
9
|
+
offpeak/venues/openai_batch.py,sha256=PyZdQQYFWyDAqrHTVQY0w7w90_KYhimT8dlrSjwYj44,5331
|
|
10
|
+
offpeak-0.1.0.dist-info/METADATA,sha256=ZVrUVElb6S83hVILwfWze57SpYcqDqCPcPXmR1eU9Rc,7009
|
|
11
|
+
offpeak-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
12
|
+
offpeak-0.1.0.dist-info/licenses/LICENSE,sha256=b5Z1Ke9S-OpiuXz9qfIFMo-6ZEMkmjjTSel0ABqfuNA,11340
|
|
13
|
+
offpeak-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
https://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 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 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 those 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
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Offpeak
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
https://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|