polydyno 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
providers.py ADDED
@@ -0,0 +1,416 @@
1
+ """LLM and simulated runners for polycracker-dyno benchmark turns."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import ssl
9
+ import time
10
+ import urllib.error
11
+ import urllib.request
12
+ from typing import Any, Literal
13
+
14
+ from dotenv import load_dotenv
15
+ from pydantic import BaseModel
16
+
17
+ load_dotenv()
18
+
19
+ ProviderName = Literal["anthropic", "openai"]
20
+
21
+ DEFAULT_MODELS: dict[ProviderName, str] = {
22
+ "anthropic": "claude-sonnet-4-5",
23
+ "openai": "gpt-4.1",
24
+ }
25
+
26
+ # USD per 1M tokens (input, output) — indicative 2026 list pricing for cost estimates.
27
+ PRICING_USD_PER_MTOK: dict[str, tuple[float, float]] = {
28
+ # OpenAI
29
+ "gpt-4.1": (2.0, 8.0),
30
+ "gpt-4.1-mini": (0.4, 1.6),
31
+ "o3": (10.0, 40.0),
32
+ "gpt-4o": (2.5, 10.0),
33
+ "gpt-4o-mini": (0.15, 0.6),
34
+ # Anthropic
35
+ "claude-sonnet-4-5": (3.0, 15.0),
36
+ "claude-opus-4-5": (15.0, 75.0),
37
+ "claude-haiku-4-5": (0.8, 4.0),
38
+ "claude-3-5-sonnet-latest": (3.0, 15.0),
39
+ }
40
+
41
+ _PROVIDER_DEFAULT_PRICING: dict[ProviderName, tuple[float, float]] = {
42
+ "anthropic": (3.0, 15.0),
43
+ "openai": (2.0, 8.0),
44
+ }
45
+
46
+ CACHED_INPUT_DISCOUNT = 0.5
47
+ HTTP_TIMEOUT_SEC = 120
48
+ ANTHROPIC_VERSION = "2023-06-01"
49
+
50
+
51
+ class ProviderHTTPError(RuntimeError):
52
+ """Non-success HTTP response from a live provider."""
53
+
54
+
55
+ def _post_json(
56
+ url: str,
57
+ payload: dict[str, Any],
58
+ headers: dict[str, str],
59
+ *,
60
+ timeout: float = HTTP_TIMEOUT_SEC,
61
+ ) -> dict[str, Any]:
62
+ body = json.dumps(payload).encode("utf-8")
63
+ request = urllib.request.Request(url, data=body, headers=headers, method="POST")
64
+ context = ssl.create_default_context()
65
+ try:
66
+ with urllib.request.urlopen(request, timeout=timeout, context=context) as response:
67
+ raw = response.read().decode("utf-8")
68
+ except urllib.error.HTTPError as exc:
69
+ detail = exc.read().decode("utf-8", errors="replace")[:500]
70
+ raise ProviderHTTPError(
71
+ f"HTTP {exc.code} from {url}: {detail or exc.reason}"
72
+ ) from exc
73
+ except urllib.error.URLError as exc:
74
+ raise ProviderHTTPError(f"Request to {url} failed: {exc.reason}") from exc
75
+ data = json.loads(raw)
76
+ if not isinstance(data, dict):
77
+ raise ProviderHTTPError(f"Expected JSON object from {url}")
78
+ return data
79
+
80
+
81
+ def _openai_uses_max_completion_tokens(model: str) -> bool:
82
+ lowered = model.lower()
83
+ if lowered.startswith("o1") or lowered.startswith("o3"):
84
+ return True
85
+ return "reasoning" in lowered
86
+
87
+
88
+ class TurnCompletion(BaseModel):
89
+ assistant_text: str
90
+ latency_ms: float
91
+ input_tokens: int
92
+ output_tokens: int
93
+ cached_input_tokens: int = 0
94
+ turn_cost_usd: float
95
+ cumulative_cost_usd: float
96
+
97
+
98
+ class LLMRunner:
99
+ """Unified Anthropic / OpenAI-compatible runner with unbounded message history."""
100
+
101
+ def __init__(
102
+ self,
103
+ provider: ProviderName = "anthropic",
104
+ model: str | None = None,
105
+ system_prompt: str | None = None,
106
+ max_output_tokens: int = 8192,
107
+ base_url: str | None = None,
108
+ ) -> None:
109
+ self.provider = provider
110
+ self.model = model or DEFAULT_MODELS[provider]
111
+ self.system_prompt = system_prompt or (
112
+ "You are a senior PostgreSQL engineer. Follow each turn precisely and "
113
+ "return the full schema in a single ```sql fenced block."
114
+ )
115
+ self.max_output_tokens = max_output_tokens
116
+ self.base_url = base_url or os.environ.get("OPENAI_BASE_URL") or None
117
+ self.messages: list[dict[str, str]] = []
118
+ self.cumulative_cost_usd: float = 0.0
119
+
120
+ def _pricing(self) -> tuple[float, float]:
121
+ return PRICING_USD_PER_MTOK.get(self.model, _PROVIDER_DEFAULT_PRICING[self.provider])
122
+
123
+ def _compute_cost_usd(
124
+ self,
125
+ input_tokens: int,
126
+ output_tokens: int,
127
+ cached_input_tokens: int = 0,
128
+ ) -> float:
129
+ in_rate, out_rate = self._pricing()
130
+ cached = min(max(cached_input_tokens, 0), max(input_tokens, 0))
131
+ uncached = max(input_tokens - cached, 0)
132
+ cached_rate = in_rate * CACHED_INPUT_DISCOUNT
133
+ return (
134
+ (uncached / 1_000_000) * in_rate
135
+ + (cached / 1_000_000) * cached_rate
136
+ + (output_tokens / 1_000_000) * out_rate
137
+ )
138
+
139
+ def _call_anthropic(self) -> tuple[str, int, int, int]:
140
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
141
+ if not api_key:
142
+ raise RuntimeError("ANTHROPIC_API_KEY is required for live Anthropic runs.")
143
+ payload: dict[str, Any] = {
144
+ "model": self.model,
145
+ "max_tokens": self.max_output_tokens,
146
+ "messages": self.messages,
147
+ }
148
+ if self.system_prompt:
149
+ payload["system"] = self.system_prompt
150
+ data = _post_json(
151
+ "https://api.anthropic.com/v1/messages",
152
+ payload,
153
+ {
154
+ "x-api-key": api_key,
155
+ "anthropic-version": ANTHROPIC_VERSION,
156
+ "content-type": "application/json",
157
+ },
158
+ )
159
+ parts = [
160
+ block.get("text", "")
161
+ for block in data.get("content") or []
162
+ if isinstance(block, dict) and block.get("type") == "text"
163
+ ]
164
+ usage = data.get("usage") or {}
165
+ cached = int(usage.get("cache_read_input_tokens") or 0)
166
+ if not cached:
167
+ cached = int(usage.get("cache_creation_input_tokens") or 0)
168
+ return (
169
+ "".join(parts),
170
+ int(usage.get("input_tokens") or 0),
171
+ int(usage.get("output_tokens") or 0),
172
+ cached,
173
+ )
174
+
175
+ def _call_openai(self) -> tuple[str, int, int, int]:
176
+ if self.base_url:
177
+ api_key = os.environ.get("OPENAI_API_KEY", "EMPTY")
178
+ else:
179
+ api_key = os.environ.get("OPENAI_API_KEY")
180
+ if not api_key:
181
+ raise RuntimeError("OPENAI_API_KEY is required for live OpenAI-compatible runs.")
182
+
183
+ root = (self.base_url or "https://api.openai.com/v1").rstrip("/")
184
+ messages: list[dict[str, str]] = []
185
+ if self.system_prompt:
186
+ messages.append({"role": "system", "content": self.system_prompt})
187
+ messages.extend(self.messages)
188
+
189
+ payload: dict[str, Any] = {
190
+ "model": self.model,
191
+ "messages": messages,
192
+ }
193
+ if _openai_uses_max_completion_tokens(self.model):
194
+ payload["max_completion_tokens"] = self.max_output_tokens
195
+ else:
196
+ payload["max_tokens"] = self.max_output_tokens
197
+
198
+ headers: dict[str, str] = {"Content-Type": "application/json"}
199
+ if api_key and api_key.strip() and api_key.strip().upper() != "EMPTY":
200
+ headers["Authorization"] = f"Bearer {api_key.strip()}"
201
+
202
+ data = _post_json(f"{root}/chat/completions", payload, headers)
203
+ choices = data.get("choices") or [{}]
204
+ choice = choices[0] if isinstance(choices[0], dict) else {}
205
+ message = choice.get("message") or {}
206
+ content = message.get("content")
207
+ if content is None:
208
+ text = ""
209
+ elif isinstance(content, str):
210
+ text = content
211
+ else:
212
+ text = str(content)
213
+
214
+ usage = data.get("usage") or {}
215
+ details = usage.get("prompt_tokens_details") or {}
216
+ if not isinstance(details, dict):
217
+ details = {}
218
+ cached = int(details.get("cached_tokens") or usage.get("cached_tokens") or 0)
219
+ return (
220
+ text,
221
+ int(usage.get("prompt_tokens") or 0),
222
+ int(usage.get("completion_tokens") or 0),
223
+ cached,
224
+ )
225
+
226
+ def run_turn(self, user_prompt: str) -> TurnCompletion:
227
+ self.messages.append({"role": "user", "content": user_prompt})
228
+ started = time.perf_counter()
229
+ if self.provider == "anthropic":
230
+ assistant_text, input_tokens, output_tokens, cached_input_tokens = self._call_anthropic()
231
+ else:
232
+ assistant_text, input_tokens, output_tokens, cached_input_tokens = self._call_openai()
233
+ latency_ms = (time.perf_counter() - started) * 1000.0
234
+ self.messages.append({"role": "assistant", "content": assistant_text})
235
+ turn_cost = self._compute_cost_usd(input_tokens, output_tokens, cached_input_tokens)
236
+ self.cumulative_cost_usd += turn_cost
237
+ return TurnCompletion(
238
+ assistant_text=assistant_text,
239
+ latency_ms=latency_ms,
240
+ input_tokens=input_tokens,
241
+ output_tokens=output_tokens,
242
+ cached_input_tokens=cached_input_tokens,
243
+ turn_cost_usd=turn_cost,
244
+ cumulative_cost_usd=self.cumulative_cost_usd,
245
+ )
246
+
247
+ def run_repair_attempt(self, feedback_prompt: str, retry_attempt: int) -> TurnCompletion:
248
+ """Execute a closed-loop self-repair turn on the live LLM."""
249
+ _ = retry_attempt
250
+ return self.run_turn(feedback_prompt)
251
+
252
+ def commit_turn_messages(self, snapshot_len: int, user_prompt: str, final_assistant_text: str) -> None:
253
+ """Rebase turn history to the committed (user_prompt, final_assistant_text) exchange."""
254
+ del self.messages[snapshot_len:]
255
+ self.messages.append({"role": "user", "content": user_prompt})
256
+ self.messages.append({"role": "assistant", "content": final_assistant_text})
257
+
258
+
259
+ def _token_estimate(text: str) -> int:
260
+ return max(1, len(text) // 4)
261
+
262
+
263
+ def _simulated_latency_ms(turn: int) -> float:
264
+ digest = int(hashlib.sha256(f"latency-{turn}".encode()).hexdigest()[:8], 16)
265
+ return float(110 + (turn * 23) + (digest % 90))
266
+
267
+
268
+ def _simulated_schema(
269
+ turn: int,
270
+ load_stage: str = "stage2",
271
+ *,
272
+ invariant_mode: str = "baseline",
273
+ retry_attempt: int = 0,
274
+ max_retries: int = 0,
275
+ ) -> str:
276
+ from workload import TURN_SPECS, generate_simulated_python, generate_simulated_sql
277
+
278
+ body = generate_simulated_sql(
279
+ turn,
280
+ invariant_mode=invariant_mode, # type: ignore[arg-type]
281
+ retry_attempt=retry_attempt,
282
+ max_retries=max_retries,
283
+ )
284
+ milestone = TURN_SPECS[turn - 1].expected_artifact if turn <= len(TURN_SPECS) else "unknown"
285
+ repair_active = invariant_mode == "verify-commit" or max_retries > 0
286
+ if not repair_active:
287
+ drift_onset = 18
288
+ if invariant_mode == "prose-repeat":
289
+ drift_onset = 21
290
+ elif invariant_mode == "ledger":
291
+ drift_onset = 26
292
+ is_collapsed = turn >= drift_onset
293
+ else:
294
+ is_collapsed = turn >= 31 or (turn in (18, 24) and retry_attempt == 0) or (turn == 18 and retry_attempt == 1)
295
+
296
+ if is_collapsed:
297
+ headline = (
298
+ f"Turn {turn} (attempt {retry_attempt}): simulated compliance drift — "
299
+ f"schema/invariant check requires verification."
300
+ )
301
+ else:
302
+ headline = f"Applied turn {turn} refactor; milestone `{milestone}` retained."
303
+ parts = [headline, f"```sql\n{body.strip()}\n```"]
304
+ if load_stage == "outlaw" and not is_collapsed:
305
+ parts.append(f"```python\n{generate_simulated_python(turn)}\n```")
306
+ return "\n\n".join(parts)
307
+
308
+
309
+ class SimulatedRunner:
310
+ """Deterministic zero-cost runner for CI/UI (--sim) with context growth modeling."""
311
+
312
+ def __init__(
313
+ self,
314
+ system_prompt: str | None = None,
315
+ load_stage: str = "stage2",
316
+ invariant_mode: str = "baseline",
317
+ max_retries: int = 0,
318
+ ) -> None:
319
+ self.system_prompt = system_prompt or "simulated"
320
+ self.load_stage = load_stage
321
+ self.invariant_mode = invariant_mode
322
+ self.max_retries = max_retries
323
+ self.messages: list[dict[str, str]] = []
324
+ self.cumulative_cost_usd: float = 0.0
325
+ self._turn: int = 0
326
+
327
+ def run_turn(self, user_prompt: str) -> TurnCompletion:
328
+ self._turn += 1
329
+ turn = self._turn
330
+ self.messages.append({"role": "user", "content": user_prompt})
331
+
332
+ assistant_text = _simulated_schema(
333
+ turn,
334
+ self.load_stage,
335
+ invariant_mode=self.invariant_mode,
336
+ retry_attempt=0,
337
+ max_retries=self.max_retries,
338
+ )
339
+ self.messages.append({"role": "assistant", "content": assistant_text})
340
+
341
+ history_blob = "\n".join(f"{m['role']}:{m['content']}" for m in self.messages)
342
+ input_tokens = _token_estimate(history_blob) + _token_estimate(self.system_prompt)
343
+ output_tokens = _token_estimate(assistant_text)
344
+ if self.invariant_mode == "baseline" and self.max_retries == 0:
345
+ input_tokens = max(1, (input_tokens - output_tokens) // 12)
346
+ elif self.invariant_mode == "prose-repeat":
347
+ input_tokens += turn * turn * 320 + (turn * 1_450)
348
+ elif self.invariant_mode == "ledger":
349
+ input_tokens = max(1, (input_tokens - output_tokens) // 10) + (turn * 95)
350
+ else:
351
+ input_tokens = max(1, (input_tokens - output_tokens) // 12)
352
+ if self.load_stage == "outlaw" and not (self.invariant_mode == "baseline" and self.max_retries == 0):
353
+ input_tokens = int(input_tokens * 1.35)
354
+ cached_input_tokens = min(input_tokens // 5, 12_000) if turn > 3 else 0
355
+
356
+ latency_ms = _simulated_latency_ms(turn)
357
+ return TurnCompletion(
358
+ assistant_text=assistant_text,
359
+ latency_ms=latency_ms,
360
+ input_tokens=input_tokens,
361
+ output_tokens=output_tokens,
362
+ cached_input_tokens=cached_input_tokens,
363
+ turn_cost_usd=0.0,
364
+ cumulative_cost_usd=0.0,
365
+ )
366
+
367
+ def run_repair_attempt(self, feedback_prompt: str, retry_attempt: int) -> TurnCompletion:
368
+ """Simulate a self-repair retry without advancing the canonical turn counter."""
369
+ _ = feedback_prompt
370
+ turn = self._turn
371
+ assistant_text = _simulated_schema(
372
+ turn,
373
+ self.load_stage,
374
+ invariant_mode=self.invariant_mode,
375
+ retry_attempt=retry_attempt,
376
+ max_retries=self.max_retries,
377
+ )
378
+ input_tokens = 240 + (turn * 12) + (retry_attempt * 85)
379
+ output_tokens = _token_estimate(assistant_text)
380
+ cached_input_tokens = min(input_tokens // 5, 12_000) if turn > 3 else 0
381
+ latency_ms = _simulated_latency_ms(turn + retry_attempt)
382
+ return TurnCompletion(
383
+ assistant_text=assistant_text,
384
+ latency_ms=latency_ms,
385
+ input_tokens=input_tokens,
386
+ output_tokens=output_tokens,
387
+ cached_input_tokens=cached_input_tokens,
388
+ turn_cost_usd=0.0,
389
+ cumulative_cost_usd=0.0,
390
+ )
391
+
392
+ def commit_turn_messages(self, snapshot_len: int, user_prompt: str, final_assistant_text: str) -> None:
393
+ """Commit only the verified (or final) turn exchange to message history."""
394
+ del self.messages[snapshot_len:]
395
+ self.messages.append({"role": "user", "content": user_prompt})
396
+ self.messages.append({"role": "assistant", "content": final_assistant_text})
397
+
398
+
399
+ def runner_from_env(
400
+ *,
401
+ sim: bool = False,
402
+ provider: ProviderName | None = None,
403
+ model: str | None = None,
404
+ base_url: str | None = None,
405
+ ) -> LLMRunner | SimulatedRunner:
406
+ if sim or os.environ.get("DYNO_MODE", "mock").lower() == "mock":
407
+ return SimulatedRunner()
408
+ chosen_provider: ProviderName = provider or _env_provider()
409
+ return LLMRunner(provider=chosen_provider, model=model, base_url=base_url)
410
+
411
+
412
+ def _env_provider() -> ProviderName:
413
+ raw = os.environ.get("DYNO_PROVIDER", "anthropic").lower()
414
+ if raw == "openai":
415
+ return "openai"
416
+ return "anthropic"
schema.sql ADDED
@@ -0,0 +1,21 @@
1
+ -- polycracker-dyno starter schema (PostgreSQL)
2
+
3
+ CREATE TABLE users (
4
+ id BIGSERIAL PRIMARY KEY,
5
+ email TEXT NOT NULL UNIQUE,
6
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
7
+ );
8
+
9
+ CREATE TABLE orders (
10
+ id BIGSERIAL PRIMARY KEY,
11
+ user_id BIGINT NOT NULL,
12
+ status TEXT NOT NULL DEFAULT 'pending',
13
+ total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
14
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
15
+ CONSTRAINT fk_user_id
16
+ FOREIGN KEY (user_id)
17
+ REFERENCES users (id)
18
+ ON DELETE CASCADE
19
+ );
20
+
21
+ CREATE INDEX idx_orders_user_id ON orders (user_id);