Coverage for src/romfarmer/farmhand/optimizer/llm_client.py: 0%

50 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1"""LLM critic client — wraps the Copilot Router via OpenAI SDK. 

2 

3Sends structured prompts to the local Copilot Router (``gcr``) and parses 

4the JSON response into a validated :class:`~.state.CriticDecision`. 

5 

6Environment variables 

7--------------------- 

8COPILOT_ROUTER_URL 

9 Base URL for the router. Default: ``http://localhost:7318/v1``. 

10CRITIC_MODEL 

11 Model name to use. Default: ``claude-haiku-4.5``. 

12CRITIC_TEMPERATURE 

13 Float in [0, 1]. Default: ``0.2`` (mostly deterministic). 

14CRITIC_MAX_RETRIES 

15 Number of JSON parse retries. Default: ``3``. 

16""" 

17 

18from __future__ import annotations 

19 

20import json 

21import logging 

22import os 

23import time 

24from typing import Any 

25 

26from .state import CriticDecision 

27 

28logger = logging.getLogger(__name__) 

29 

30_ROUTER_URL = os.getenv("COPILOT_ROUTER_URL", "http://localhost:7318/v1") 

31_MODEL = os.getenv("CRITIC_MODEL", "claude-haiku-4.5") 

32_TEMPERATURE = float(os.getenv("CRITIC_TEMPERATURE", "0.2")) 

33_MAX_RETRIES = int(os.getenv("CRITIC_MAX_RETRIES", "3")) 

34 

35 

36def call_critic(system_prompt: str, user_payload: dict[str, Any]) -> CriticDecision: 

37 """Call the LLM critic and return a validated :class:`CriticDecision`. 

38 

39 Args: 

40 system_prompt: System prompt from :mod:`.prompts`. 

41 user_payload: Structured iteration data (thresholds, sizes, history). 

42 

43 Returns: 

44 Parsed and validated :class:`CriticDecision`. 

45 

46 Raises: 

47 RuntimeError: If the LLM returns malformed JSON after all retries. 

48 """ 

49 try: 

50 from openai import OpenAI # type: ignore 

51 except ImportError as exc: 

52 raise ImportError( 

53 "openai package is required for the budget optimizer. " 

54 "Install with: pip install 'romfarmer[optimizer]'" 

55 ) from exc 

56 

57 client = OpenAI(base_url=_ROUTER_URL, api_key="not-required") 

58 

59 user_message = ( 

60 "Analyze the following build state and return your threshold adjustments " 

61 "as a JSON object.\n\n" + json.dumps(user_payload, indent=2) 

62 ) 

63 

64 last_exc: Exception = RuntimeError("no attempts made") 

65 for attempt in range(1, _MAX_RETRIES + 1): 

66 try: 

67 response = client.chat.completions.create( 

68 model=_MODEL, 

69 temperature=_TEMPERATURE, 

70 messages=[ 

71 {"role": "system", "content": system_prompt}, 

72 {"role": "user", "content": user_message}, 

73 ], 

74 ) 

75 raw = response.choices[0].message.content or "" 

76 decision = _parse_decision(raw) 

77 logger.debug(f"Critic response (attempt {attempt}): {decision.rationale[:120]}") 

78 return decision 

79 except (ValueError, KeyError, json.JSONDecodeError) as exc: 

80 last_exc = exc 

81 logger.warning(f"Critic parse error (attempt {attempt}/{_MAX_RETRIES}): {exc}") 

82 time.sleep(0.5 * attempt) 

83 

84 raise RuntimeError( 

85 f"LLM critic returned invalid JSON after {_MAX_RETRIES} attempts: {last_exc}" 

86 ) from last_exc 

87 

88 

89def _parse_decision(raw: str) -> CriticDecision: 

90 """Extract JSON block from the LLM output and validate it.""" 

91 # Strip markdown code fences if present 

92 text = raw.strip() 

93 if "```" in text: 

94 # Extract content between first ``` and last ``` 

95 start = text.find("```") + 3 

96 if text[start:].startswith("json"): 

97 start += 4 

98 end = text.rfind("```") 

99 text = text[start:end].strip() 

100 

101 data = json.loads(text) 

102 

103 # Validate required keys 

104 if "thresholds" not in data: 

105 raise KeyError("Missing 'thresholds' key in critic response") 

106 if "rationale" not in data: 

107 raise KeyError("Missing 'rationale' key in critic response") 

108 

109 direction = data.get("expected_direction", "hold") 

110 if direction not in ("grow", "shrink", "hold"): 

111 direction = "hold" 

112 

113 # Coerce threshold values to float, clamp to [0.0, 1.0] 

114 thresholds = {str(k): max(0.0, min(1.0, float(v))) for k, v in data["thresholds"].items()} 

115 

116 return CriticDecision( 

117 thresholds=thresholds, 

118 rationale=str(data["rationale"])[:1000], 

119 expected_direction=direction, 

120 )