|
| 1 | +"""Shared base class for pipeline agents. |
| 2 | +
|
| 3 | +Every agent in the code-generation pipeline constructs a ``ChatAnthropic`` LLM |
| 4 | +and loads a system prompt from ``prompts/``. ``BaseAgent`` centralises that |
| 5 | +plumbing so concrete agents only declare model, token budget, and prompt name. |
| 6 | +``TesterBaseAgent`` extends it with the generation-aware fallback chain used |
| 7 | +by the self-evolving tester. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +from pathlib import Path |
| 13 | +from typing import ClassVar |
| 14 | + |
| 15 | +from langchain_anthropic import ChatAnthropic |
| 16 | + |
| 17 | +from config import MAX_TOKENS |
| 18 | + |
| 19 | +_PROMPTS_DIR = Path(__file__).parent.parent / "prompts" |
| 20 | + |
| 21 | + |
| 22 | +class BaseAgent: |
| 23 | + """Common LLM + system-prompt wiring for pipeline agents. |
| 24 | +
|
| 25 | + Subclasses declare three class-level attributes and inherit the rest: |
| 26 | +
|
| 27 | + - ``model_name``: Anthropic model id (usually sourced from ``config.py``). |
| 28 | + - ``max_tokens_key``: key into ``config.MAX_TOKENS`` for this agent's cap. |
| 29 | + - ``prompt_name``: basename (without ``.md``) of the file in ``prompts/``. |
| 30 | + """ |
| 31 | + |
| 32 | + model_name: ClassVar[str] |
| 33 | + max_tokens_key: ClassVar[str] |
| 34 | + prompt_name: ClassVar[str] |
| 35 | + |
| 36 | + def __init__(self) -> None: |
| 37 | + self.llm: ChatAnthropic = ChatAnthropic( # type: ignore[call-arg] |
| 38 | + model=self.model_name, |
| 39 | + max_tokens=MAX_TOKENS[self.max_tokens_key], |
| 40 | + ) |
| 41 | + self.system_prompt: str = self._load_prompt() |
| 42 | + |
| 43 | + def _load_prompt(self) -> str: |
| 44 | + """Load ``prompts/{prompt_name}.md`` as the system prompt.""" |
| 45 | + return (_PROMPTS_DIR / f"{self.prompt_name}.md").read_text() |
| 46 | + |
| 47 | + |
| 48 | +class TesterBaseAgent(BaseAgent): |
| 49 | + """Tester agent with generation-aware prompt resolution. |
| 50 | +
|
| 51 | + Generation 0 uses the original ``prompts/tester.md``. Generation N > 0 |
| 52 | + uses ``prompts/tester_gen_{N}.txt``, falling back to the nearest earlier |
| 53 | + generation that exists, then to the base prompt. |
| 54 | + """ |
| 55 | + |
| 56 | + prompt_name: ClassVar[str] = "tester" |
| 57 | + generation: int |
| 58 | + |
| 59 | + def __init__(self, generation: int = 0) -> None: |
| 60 | + self.generation = generation |
| 61 | + super().__init__() |
| 62 | + |
| 63 | + def _load_prompt(self) -> str: |
| 64 | + if self.generation == 0: |
| 65 | + return (_PROMPTS_DIR / "tester.md").read_text() |
| 66 | + for gen in range(self.generation, 0, -1): |
| 67 | + path = _PROMPTS_DIR / f"tester_gen_{gen}.txt" |
| 68 | + if path.exists(): |
| 69 | + return path.read_text() |
| 70 | + return (_PROMPTS_DIR / "tester.md").read_text() |
0 commit comments