parrot_openrouter.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. """
  2. parrot_openrouter: same as the upstream `parrot` example but the LLM call goes
  3. through OpenRouter (OpenAI SDK) instead of Anthropic native. Lets us run an
  4. end-to-end evolution with whatever model the user already has paid access to.
  5. Run with:
  6. uv --project darwinian_evolver run python parrot_openrouter.py \
  7. --num_iterations 3 --output_dir ~/.hermes/cache/scratch/parrot_out
  8. Reads `OPENROUTER_API_KEY` from the environment.
  9. """
  10. from __future__ import annotations
  11. import argparse
  12. import os
  13. import sys
  14. from pathlib import Path
  15. import jinja2
  16. from openai import OpenAI
  17. # Vendored problem types from upstream (AGPL — only run via subprocess in production)
  18. from darwinian_evolver.cli_common import build_hyperparameter_config_from_args
  19. from darwinian_evolver.cli_common import register_hyperparameter_args
  20. from darwinian_evolver.cli_common import parse_learning_log_view_type
  21. from darwinian_evolver.evolve_problem_loop import EvolveProblemLoop
  22. from darwinian_evolver.learning_log import LearningLogEntry
  23. from darwinian_evolver.problem import EvaluationFailureCase
  24. from darwinian_evolver.problem import EvaluationResult
  25. from darwinian_evolver.problem import Evaluator
  26. from darwinian_evolver.problem import Mutator
  27. from darwinian_evolver.problem import Organism
  28. from darwinian_evolver.problem import Problem
  29. DEFAULT_MODEL = os.environ.get("EVOLVER_MODEL", "openai/gpt-4o-mini")
  30. def _client() -> OpenAI:
  31. key = os.environ.get("OPENROUTER_API_KEY")
  32. if not key:
  33. sys.exit("OPENROUTER_API_KEY is not set")
  34. return OpenAI(api_key=key, base_url="https://openrouter.ai/api/v1")
  35. def _prompt_llm(prompt: str) -> str:
  36. try:
  37. r = _client().chat.completions.create(
  38. model=DEFAULT_MODEL,
  39. max_tokens=1024,
  40. messages=[{"role": "user", "content": prompt}],
  41. )
  42. return r.choices[0].message.content or ""
  43. except Exception as e:
  44. # Treat any provider error (rate limit, content filter, schema reject)
  45. # as a failed response. The evolver will simply see this as a low score
  46. # on this organism and move on — much friendlier than killing the run.
  47. return f"<LLM_ERROR: {type(e).__name__}: {e}>"
  48. class ParrotOrganism(Organism):
  49. prompt_template: str
  50. def run(self, phrase: str) -> str:
  51. try:
  52. prompt = jinja2.Template(self.prompt_template).render(phrase=phrase)
  53. except jinja2.exceptions.TemplateError as e:
  54. return f"Error rendering prompt: {e}"
  55. if not prompt:
  56. return ""
  57. return _prompt_llm(prompt)
  58. class ParrotEvaluationFailureCase(EvaluationFailureCase):
  59. phrase: str
  60. response: str
  61. class ImproveParrotMutator(Mutator[ParrotOrganism, ParrotEvaluationFailureCase]):
  62. IMPROVEMENT_PROMPT_TEMPLATE = """
  63. We want to build a prompt that causes an LLM to repeat back a given phrase verbatim.
  64. The current prompt template is:
  65. ```
  66. {{ organism.prompt_template }}
  67. ```
  68. Unfortunately, on this phrase:
  69. ```
  70. {{ failure_case.phrase }}
  71. ```
  72. the LLM responded with:
  73. ```
  74. {{ failure_case.response }}
  75. ```
  76. Diagnose what went wrong, then propose an improved prompt template. Put the new
  77. template in the LAST triple-backtick block of your response.
  78. """.strip()
  79. def mutate(
  80. self,
  81. organism: ParrotOrganism,
  82. failure_cases: list[ParrotEvaluationFailureCase],
  83. learning_log_entries: list[LearningLogEntry],
  84. ) -> list[ParrotOrganism]:
  85. fc = failure_cases[0]
  86. prompt = jinja2.Template(self.IMPROVEMENT_PROMPT_TEMPLATE).render(
  87. organism=organism, failure_case=fc
  88. )
  89. try:
  90. resp = _prompt_llm(prompt)
  91. parts = resp.split("```")
  92. if len(parts) < 3:
  93. return []
  94. new_tpl = parts[-2].strip()
  95. return [ParrotOrganism(prompt_template=new_tpl)]
  96. except Exception as e:
  97. print(f"mutate error: {e}", file=sys.stderr)
  98. return []
  99. class ParrotEvaluator(Evaluator[ParrotOrganism, EvaluationResult, ParrotEvaluationFailureCase]):
  100. TRAINABLE_PHRASES = [
  101. "Hello world.",
  102. "bla",
  103. "Bla",
  104. "bla.",
  105. '"bla bla".',
  106. "Just say 'foo' once with no extra words.",
  107. ]
  108. HOLDOUT_PHRASES = [
  109. "bla, but only once.",
  110. "'bla'",
  111. ]
  112. def evaluate(self, organism: ParrotOrganism) -> EvaluationResult:
  113. train_fails: list[ParrotEvaluationFailureCase] = []
  114. hold_fails: list[ParrotEvaluationFailureCase] = []
  115. for i, p in enumerate(self.TRAINABLE_PHRASES):
  116. r = organism.run(p)
  117. if r != p:
  118. train_fails.append(ParrotEvaluationFailureCase(
  119. phrase=p, response=r, data_point_id=f"trainable_{i}"))
  120. for i, p in enumerate(self.HOLDOUT_PHRASES):
  121. r = organism.run(p)
  122. if r != p:
  123. hold_fails.append(ParrotEvaluationFailureCase(
  124. phrase=p, response=r, data_point_id=f"holdout_{i}"))
  125. n_total = len(self.TRAINABLE_PHRASES) + len(self.HOLDOUT_PHRASES)
  126. n_ok = n_total - len(train_fails) - len(hold_fails)
  127. return EvaluationResult(
  128. score=n_ok / n_total,
  129. trainable_failure_cases=train_fails,
  130. holdout_failure_cases=hold_fails,
  131. # Always viable. Even a 0-score seed is a valid starting point; the
  132. # mutator should still get a chance to fix it.
  133. is_viable=True,
  134. )
  135. def make_problem() -> Problem:
  136. return Problem[ParrotOrganism, EvaluationResult, ParrotEvaluationFailureCase](
  137. evaluator=ParrotEvaluator(),
  138. mutators=[ImproveParrotMutator()],
  139. initial_organism=ParrotOrganism(prompt_template="Say {{ phrase }}"),
  140. )
  141. def main() -> int:
  142. ap = argparse.ArgumentParser()
  143. register_hyperparameter_args(ap.add_argument_group("hyperparameters"))
  144. ap.add_argument("--num_iterations", type=int, default=3)
  145. ap.add_argument("--mutator_concurrency", type=int, default=4)
  146. ap.add_argument("--evaluator_concurrency", type=int, default=4)
  147. ap.add_argument("--output_dir", type=str, required=True)
  148. args = ap.parse_args()
  149. out = Path(args.output_dir)
  150. out.mkdir(parents=True, exist_ok=True)
  151. hp = build_hyperparameter_config_from_args(args)
  152. loop = EvolveProblemLoop(
  153. problem=make_problem(),
  154. learning_log_view_type=parse_learning_log_view_type(hp.learning_log_view_type),
  155. num_parents_per_iteration=hp.num_parents_per_iteration,
  156. mutator_concurrency=args.mutator_concurrency,
  157. evaluator_concurrency=args.evaluator_concurrency,
  158. fixed_midpoint_score=hp.fixed_midpoint_score,
  159. midpoint_score_percentile=hp.midpoint_score_percentile,
  160. sharpness=hp.sharpness,
  161. novelty_weight=hp.novelty_weight,
  162. batch_size=hp.batch_size,
  163. should_verify_mutations=hp.verify_mutations,
  164. )
  165. import json
  166. log_path = out / "results.jsonl"
  167. snap_dir = out / "snapshots"
  168. snap_dir.mkdir(exist_ok=True)
  169. print("Evaluating initial organism...")
  170. for snap in loop.run(num_iterations=args.num_iterations):
  171. (snap_dir / f"iteration_{snap.iteration}.pkl").write_bytes(snap.snapshot)
  172. _, best_eval = snap.best_organism_result
  173. print(f"iter={snap.iteration} pop={snap.population_size} "
  174. f"best_score={best_eval.score:.3f}")
  175. with log_path.open("a") as f:
  176. f.write(json.dumps({
  177. "iteration": snap.iteration,
  178. "best_score": best_eval.score,
  179. "pop_size": snap.population_size,
  180. "score_percentiles": {str(k): v for k, v in snap.score_percentiles.items()},
  181. }) + "\n")
  182. print(f"\nDone. Results in: {out}")
  183. return 0
  184. if __name__ == "__main__":
  185. sys.exit(main())