openevolve-bedrock 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.
@@ -0,0 +1,43 @@
1
+ # Copyright 2026 Scott Friedman
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ openevolve-bedrock: Amazon Bedrock as the LLM backend for OpenEvolve.
17
+
18
+ Importing this package registers the ``bedrock`` provider with OpenEvolve's
19
+ LLM ensemble. In a config.yaml::
20
+
21
+ llm:
22
+ provider: bedrock
23
+ api_base: aws://us-west-2 # Converse API, SigV4 (or Bedrock API key)
24
+ models:
25
+ - name: us.amazon.nova-2-lite-v1:0
26
+ weight: 0.8
27
+ - name: us.anthropic.claude-sonnet-5-5
28
+ weight: 0.2
29
+
30
+ or, for the OpenAI-compatible Mantle endpoint::
31
+
32
+ llm:
33
+ provider: bedrock
34
+ api_base: https://bedrock-mantle.us-east-1.api.aws/v1
35
+ api_key: "${AWS_BEARER_TOKEN_BEDROCK}"
36
+ """
37
+
38
+ from openevolve_bedrock.provider import BedrockLLM, register
39
+
40
+ __version__ = "0.2.0"
41
+ __all__ = ["BedrockLLM", "register", "__version__"]
42
+
43
+ register()
@@ -0,0 +1,10 @@
1
+ # Copyright 2026 Scott Friedman
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """``python -m openevolve_bedrock`` entry point."""
4
+
5
+ import sys
6
+
7
+ from openevolve_bedrock.cli import main
8
+
9
+ if __name__ == "__main__":
10
+ sys.exit(main())
@@ -0,0 +1,380 @@
1
+ # Copyright 2026 Scott Friedman
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ oe-bedrock — run OpenEvolve on Amazon Bedrock and account for what it cost.
17
+
18
+ oe-bedrock run PROGRAM EVALUATOR --config cfg.yaml [--iterations N]
19
+ [--target-score T] [--budget-usd X --pricing pricing.yaml] [...]
20
+ oe-bedrock models [--region R] [--vendor anthropic] [--profiles]
21
+ oe-bedrock check --config cfg.yaml # one tiny call per model
22
+ oe-bedrock cost LEDGER --pricing pricing.yaml [--output-dir DIR --metric M --threshold X]
23
+ oe-bedrock install-hook [--remove] # auto-import in every Python process
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import os
31
+ import sys
32
+ import time
33
+ from pathlib import Path
34
+ from typing import Dict, List, Optional
35
+
36
+ import yaml
37
+
38
+ from openevolve_bedrock import __version__, register
39
+ from openevolve_bedrock import ledger as led
40
+ from openevolve_bedrock import stopping
41
+ from openevolve_bedrock.ledger import DEFAULT_LEDGER_ENV, DEFAULT_LEDGER_NAME
42
+
43
+
44
+ def _p(*a, **k):
45
+ print(*a, **k, flush=True)
46
+
47
+
48
+ # --------------------------------------------------------------------------
49
+ # run
50
+ # --------------------------------------------------------------------------
51
+
52
+
53
+ def cmd_run(args: argparse.Namespace, passthrough: List[str]) -> int:
54
+ register()
55
+ # Default the ledger into OpenEvolve's output directory so one run == one ledger.
56
+ if DEFAULT_LEDGER_ENV not in os.environ:
57
+ out = args.output or str(Path(args.initial_program).resolve().parent / "openevolve_output")
58
+ os.environ[DEFAULT_LEDGER_ENV] = str(Path(out) / DEFAULT_LEDGER_NAME)
59
+ _p(f"openevolve-bedrock {__version__}: ledger -> {os.environ[DEFAULT_LEDGER_ENV]}")
60
+ if args.budget_usd is not None:
61
+ if not args.pricing:
62
+ _p("--budget-usd needs --pricing")
63
+ return 2
64
+ os.environ[stopping.BUDGET_ENV] = str(args.budget_usd)
65
+ os.environ[stopping.PRICING_ENV] = str(Path(args.pricing).resolve())
66
+ stopping.budget_from_env() # fail now on a bad pricing file, not mid-run
67
+ _p(f"budget ${args.budget_usd:g} priced from {os.environ[stopping.PRICING_ENV]}")
68
+
69
+ from openevolve.cli import main as oe_main
70
+
71
+ argv = ["openevolve-run", args.initial_program, args.evaluation_file]
72
+ if args.config:
73
+ argv += ["--config", args.config]
74
+ if args.output:
75
+ argv += ["--output", args.output]
76
+ if args.iterations is not None:
77
+ argv += ["--iterations", str(args.iterations)]
78
+ if args.checkpoint:
79
+ argv += ["--checkpoint", args.checkpoint]
80
+ argv += passthrough
81
+ sys.argv = argv
82
+ return int(oe_main() or 0)
83
+
84
+
85
+ # --------------------------------------------------------------------------
86
+ # models
87
+ # --------------------------------------------------------------------------
88
+
89
+
90
+ def _bedrock_control_client(region: Optional[str], profile: Optional[str]):
91
+ import boto3
92
+
93
+ region = region or os.environ.get("OE_BEDROCK_REGION") or os.environ.get("AWS_REGION") \
94
+ or os.environ.get("AWS_DEFAULT_REGION")
95
+ if not region:
96
+ raise SystemExit("no region: pass --region or export AWS_REGION / OE_BEDROCK_REGION")
97
+ session = boto3.Session(profile_name=profile or os.environ.get("OE_BEDROCK_PROFILE") or None,
98
+ region_name=region)
99
+ return session.client("bedrock"), region
100
+
101
+
102
+ def cmd_models(args: argparse.Namespace) -> int:
103
+ from openevolve_bedrock.provider import _base_model_id, _vendor
104
+
105
+ client, region = _bedrock_control_client(args.region, args.profile)
106
+ want = (args.vendor or "").lower()
107
+
108
+ def matches(model_id: str, provider_name: str = "") -> bool:
109
+ return not want or want == _vendor(model_id) or want in provider_name.lower()
110
+
111
+ resp = client.list_foundation_models(byOutputModality="TEXT")
112
+ lifecycle: Dict[str, str] = {}
113
+ rows = []
114
+ for m in resp.get("modelSummaries", []):
115
+ if "TEXT" not in (m.get("inputModalities") or []):
116
+ continue
117
+ mid = m["modelId"]
118
+ life = (m.get("modelLifecycle") or {}).get("status", "")
119
+ lifecycle[mid] = life
120
+ types = m.get("inferenceTypesSupported") or []
121
+ if not args.all and not {"ON_DEMAND", "INFERENCE_PROFILE"} & set(types):
122
+ continue # provisioned-only
123
+ if not matches(mid, m.get("providerName", "")):
124
+ continue
125
+ call = "on-demand" if "ON_DEMAND" in types else "profile" if "INFERENCE_PROFILE" in types else "-"
126
+ rows.append((mid, m.get("providerName", ""), call, life))
127
+ rows.sort()
128
+ _p(f"# text models in {region} (call: on-demand = use the id; profile = use a us./global. id, see --profiles)")
129
+ for r in rows:
130
+ _p(f"{r[0]:<52} {r[1]:<12} {r[2]:<10} {r[3]}")
131
+
132
+ if args.profiles:
133
+ _p(f"\n# inference profiles in {region} for text models (use these ids for profile-only models)")
134
+ paginator = client.get_paginator("list_inference_profiles")
135
+ prof = []
136
+ for page in paginator.paginate():
137
+ for p in page.get("inferenceProfileSummaries", []):
138
+ pid = p.get("inferenceProfileId", "")
139
+ base = _base_model_id(pid)
140
+ if base not in lifecycle and not args.all:
141
+ continue # image, embedding, rerank ...
142
+ if not matches(pid):
143
+ continue
144
+ prof.append((pid, p.get("status", ""), lifecycle.get(base, "")))
145
+ for r in sorted(prof):
146
+ _p(f"{r[0]:<60} {r[1]:<8} model {r[2]}")
147
+ return 0
148
+
149
+
150
+ # --------------------------------------------------------------------------
151
+ # check
152
+ # --------------------------------------------------------------------------
153
+
154
+
155
+ def _models_from_config(path: str):
156
+ from openevolve.config import Config
157
+
158
+ cfg = Config.from_yaml(path)
159
+ seen = {}
160
+ for m in list(cfg.llm.models) + list(cfg.llm.evaluator_models):
161
+ if m.name and m.name not in seen:
162
+ seen[m.name] = m
163
+ return cfg, list(seen.values())
164
+
165
+
166
+ def cmd_check(args: argparse.Namespace) -> int:
167
+ import asyncio
168
+
169
+ register()
170
+ from openevolve_bedrock.provider import BedrockLLM
171
+
172
+ os.environ.setdefault(DEFAULT_LEDGER_ENV, "off")
173
+ cfg, models = _models_from_config(args.config)
174
+ if not models:
175
+ _p("no models in config")
176
+ return 1
177
+ provider = cfg.llm.provider
178
+ if provider != "bedrock":
179
+ _p(f"warning: llm.provider is {provider!r}, expected 'bedrock'")
180
+ ok = True
181
+ # ~5.4K tokens: above every model's cache minimum (512-4096; Claude Haiku 4.5: 4096)
182
+ long_system = ("You are a careful assistant. " * 900) if args.cache_probe else None
183
+ for m in models:
184
+ try:
185
+ llm = BedrockLLM(m)
186
+ # With --cache-probe the second identical call should read what the first wrote.
187
+ for call in (1, 2) if long_system else (1,):
188
+ t0 = time.monotonic()
189
+ text = asyncio.run(
190
+ llm.generate_with_context(
191
+ system_message=long_system or "Reply with the single word OK.",
192
+ messages=[{"role": "user", "content": "Reply with the single word OK."}],
193
+ max_tokens=256, # room for reasoning models
194
+ )
195
+ )
196
+ dt = (time.monotonic() - t0) * 1000
197
+ u = llm.last_usage or {}
198
+ tag = f" #{call}" if long_system else ""
199
+ _p(f"OK {m.name + tag:<60} {llm.transport.name:<9} {dt:6.0f} ms "
200
+ f"in={u.get('prompt_tokens')} out={u.get('completion_tokens')} "
201
+ f"cache_read={u.get('cache_read_tokens')} cache_write={u.get('cache_write_tokens')} "
202
+ f"-> {text.strip()[:30]!r}")
203
+ except Exception as e: # noqa: BLE001 - report everything
204
+ ok = False
205
+ _p(f"FAIL {m.name:<60} {type(e).__name__}: {e}")
206
+ return 0 if ok else 2
207
+
208
+
209
+ # --------------------------------------------------------------------------
210
+ # cost
211
+ # --------------------------------------------------------------------------
212
+
213
+
214
+ def cmd_cost(args: argparse.Namespace) -> int:
215
+ ledger_path = Path(args.ledger)
216
+ if ledger_path.is_dir():
217
+ ledger_path = ledger_path / DEFAULT_LEDGER_NAME
218
+ if not ledger_path.is_file():
219
+ _p(f"no ledger at {ledger_path}")
220
+ return 1
221
+ pricing = led.load_pricing(Path(args.pricing)) if args.pricing else {}
222
+ records = list(led.read(ledger_path))
223
+
224
+ until = None
225
+ hit = None
226
+ if args.threshold is not None:
227
+ out_dir = Path(args.output_dir) if args.output_dir else ledger_path.parent
228
+ hit = led.first_checkpoint_at_threshold(out_dir, args.metric, args.threshold)
229
+ if hit is None:
230
+ _p(f"threshold {args.metric} >= {args.threshold} not reached in {out_dir}/checkpoints")
231
+ else:
232
+ until = hit.reached_ts
233
+
234
+ s = led.summarize(records, pricing, until_ts=until)
235
+ if args.json:
236
+ payload = {
237
+ "ledger": str(ledger_path),
238
+ "calls": s.total_calls,
239
+ "usd": round(s.total_usd, 6),
240
+ "input_tokens": s.input_tokens,
241
+ "output_tokens": s.output_tokens,
242
+ "cache_read_tokens": s.cache_read_tokens,
243
+ "cache_write_tokens": s.cache_write_tokens,
244
+ "throttled": s.throttled,
245
+ "by_model": {k: {**v, "usd": round(v["usd"], 6)} for k, v in s.by_model.items()},
246
+ "evals": {"count": s.evals, "usd": round(s.eval_usd, 6), "seconds": round(s.eval_s, 1),
247
+ "worker_seconds": round(s.eval_run_s, 1), "unpriced": s.evals_unpriced},
248
+ "usd_with_evals": round(s.total_usd + s.eval_usd, 6),
249
+ "unpriced_models": s.unpriced_models,
250
+ "threshold": None if hit is None else {
251
+ "metric": args.metric, "value": hit.metric_value, "iteration": hit.iteration,
252
+ "checkpoint": str(hit.checkpoint_dir),
253
+ },
254
+ }
255
+ _p(json.dumps(payload, indent=2))
256
+ return 0
257
+
258
+ _p(f"ledger: {ledger_path}")
259
+ if hit is not None:
260
+ _p(f"first checkpoint with {args.metric} >= {args.threshold}: "
261
+ f"iteration {hit.iteration} ({args.metric}={hit.metric_value:.6g}); "
262
+ f"counting calls up to that point")
263
+ _p(f"{'model':<58}{'calls':>7}{'in':>10}{'out':>9}{'cache_rd':>10}{'cache_wr':>10}{'USD':>11}")
264
+ for model, v in sorted(s.by_model.items()):
265
+ usd = f"{v['usd']:.4f}" if model not in s.unpriced_models else " n/a"
266
+ _p(f"{model:<58}{v['calls']:>7}{v['input_tokens']:>10}{v['output_tokens']:>9}"
267
+ f"{v['cache_read_tokens']:>10}{v['cache_write_tokens']:>10}{usd:>11}")
268
+ _p(f"{'total':<58}{s.total_calls:>7}{s.input_tokens:>10}{s.output_tokens:>9}"
269
+ f"{s.cache_read_tokens:>10}{s.cache_write_tokens:>10}{s.total_usd:>11.4f}")
270
+ if s.throttled:
271
+ _p(f"throttled responses absorbed by retry: {s.throttled}")
272
+ if s.unpriced_models:
273
+ _p("unpriced models (add to pricing.yaml): " + ", ".join(s.unpriced_models))
274
+ if s.evals:
275
+ unpriced = f", {s.evals_unpriced} without a cost estimate" if s.evals_unpriced else ""
276
+ _p(f"remote evaluations: {s.evals}, {s.eval_run_s / 3600:.2f} worker-h "
277
+ f"({s.eval_s / 3600:.2f} h submit-to-result), ${s.eval_usd:.4f}{unpriced}")
278
+ _p(f"LLM + evaluations: ${s.total_usd + s.eval_usd:.4f}")
279
+ return 0
280
+
281
+
282
+ # --------------------------------------------------------------------------
283
+ # install-hook
284
+ # --------------------------------------------------------------------------
285
+
286
+
287
+ def _site_packages_dir() -> Path:
288
+ import sysconfig
289
+
290
+ return Path(sysconfig.get_paths()["purelib"])
291
+
292
+
293
+ def cmd_install_hook(args: argparse.Namespace) -> int:
294
+ """
295
+ Write a .pth file so every Python process in this environment imports
296
+ openevolve_bedrock at startup. Only needed when running OpenEvolve via its
297
+ own CLI (openevolve-run.py) with process-parallel workers; `oe-bedrock run`
298
+ does not need it.
299
+ """
300
+ target = _site_packages_dir() / "openevolve_bedrock_autoload.pth"
301
+ if args.remove:
302
+ if target.exists():
303
+ target.unlink()
304
+ _p(f"removed {target}")
305
+ else:
306
+ _p(f"nothing to remove at {target}")
307
+ return 0
308
+ target.write_text("import openevolve_bedrock\n", encoding="utf-8")
309
+ _p(f"wrote {target}")
310
+ return 0
311
+
312
+
313
+ # --------------------------------------------------------------------------
314
+ # argparse
315
+ # --------------------------------------------------------------------------
316
+
317
+
318
+ def build_parser() -> argparse.ArgumentParser:
319
+ p = argparse.ArgumentParser(prog="oe-bedrock", description=__doc__,
320
+ formatter_class=argparse.RawDescriptionHelpFormatter)
321
+ p.add_argument("--version", action="version", version=f"openevolve-bedrock {__version__}")
322
+ sub = p.add_subparsers(dest="cmd", required=True)
323
+
324
+ r = sub.add_parser("run", help="run OpenEvolve with the bedrock provider registered")
325
+ r.add_argument("initial_program")
326
+ r.add_argument("evaluation_file")
327
+ r.add_argument("--config", "-c")
328
+ r.add_argument("--output", "-o")
329
+ r.add_argument("--iterations", "-i", type=int)
330
+ r.add_argument("--checkpoint")
331
+ r.add_argument("--budget-usd", type=float,
332
+ help="stop once the ledger, priced with --pricing, reaches this many USD")
333
+ r.add_argument("--pricing", help="pricing.yaml for --budget-usd")
334
+
335
+ m = sub.add_parser("models", help="list text models / inference profiles in a region")
336
+ m.add_argument("--region")
337
+ m.add_argument("--profile", help="boto3 profile")
338
+ m.add_argument("--vendor", help="filter by vendor, e.g. anthropic, amazon, mistral, deepseek, qwen")
339
+ m.add_argument("--profiles", action="store_true", help="also list inference profiles")
340
+ m.add_argument("--all", action="store_true",
341
+ help="include provisioned-only models and non-text profiles")
342
+
343
+ c = sub.add_parser("check", help="make one short call per model in a config")
344
+ c.add_argument("--config", "-c", required=True)
345
+ c.add_argument("--cache-probe", action="store_true",
346
+ help="send a ~5K-token system prompt twice; the second call should read the cache")
347
+
348
+ k = sub.add_parser("cost", help="summarize a ledger; optionally $ to a metric threshold")
349
+ k.add_argument("ledger", help="ledger file or OpenEvolve output dir")
350
+ k.add_argument("--pricing", help="pricing.yaml (USD per 1K tokens)")
351
+ k.add_argument("--output-dir", help="OpenEvolve output dir with checkpoints/ (default: ledger dir)")
352
+ k.add_argument("--metric", default="combined_score")
353
+ k.add_argument("--threshold", type=float)
354
+ k.add_argument("--json", action="store_true")
355
+
356
+ h = sub.add_parser("install-hook", help="auto-import this package in every Python process")
357
+ h.add_argument("--remove", action="store_true")
358
+ return p
359
+
360
+
361
+ def main(argv: Optional[List[str]] = None) -> int:
362
+ argv = list(sys.argv[1:] if argv is None else argv)
363
+ # `run` forwards unknown flags to openevolve-run.
364
+ if argv and argv[0] == "run":
365
+ args, passthrough = build_parser().parse_known_args(argv)
366
+ return cmd_run(args, passthrough)
367
+ args = build_parser().parse_args(argv)
368
+ if args.cmd == "models":
369
+ return cmd_models(args)
370
+ if args.cmd == "check":
371
+ return cmd_check(args)
372
+ if args.cmd == "cost":
373
+ return cmd_cost(args)
374
+ if args.cmd == "install-hook":
375
+ return cmd_install_hook(args)
376
+ return 1
377
+
378
+
379
+ if __name__ == "__main__":
380
+ sys.exit(main())