Repository navigation
Expand file tree
/
Copy pathnodes.py
More file actions
230 lines (188 loc) · 8.91 KB
/
Copy pathnodes.py
File metadata and controls
230 lines (188 loc) · 8.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""DAG node primitives: TaskNode, BinaryJudgeNode, NonBinaryJudgeNode, VerdictNode."""
from __future__ import annotations
import json
import re
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Union
from minival.types import TestCase, TestCaseParams
if TYPE_CHECKING:
from minival.llm.base import BaseLLM
from minival.metrics.base import BaseMetric
# ---------------------------------------------------------------------------
# JSON repair helper
# ---------------------------------------------------------------------------
def _parse_json_lenient(text: str) -> Any:
"""Parse JSON from an LLM response, stripping markdown fences and fixing common issues."""
# Strip markdown code fences
text = re.sub(r"```(?:json)?\s*", "", text).strip().rstrip("`").strip()
# Remove trailing commas before closing braces/brackets
text = re.sub(r",\s*([}\]])", r"\1", text)
return json.loads(text)
def _coerce_bool(value: Any) -> bool | None:
"""Best-effort bool coercion for LLM JSON output values."""
if isinstance(value, bool):
return value
if isinstance(value, str):
normalized = value.strip().lower()
if normalized in {"true", "yes", "1"}:
return True
if normalized in {"false", "no", "0"}:
return False
return None
if isinstance(value, int) and value in {0, 1}:
return bool(value)
return None
# ---------------------------------------------------------------------------
# Shared context accumulated during DAG traversal
# ---------------------------------------------------------------------------
@dataclass
class TraversalContext:
test_case: TestCase
labeled_outputs: dict[str, Any] = field(default_factory=dict)
def fork(self) -> "TraversalContext":
"""Create a shallow branch-local copy for concurrent traversal."""
return TraversalContext(
test_case=self.test_case,
labeled_outputs=dict(self.labeled_outputs),
)
def build_context_section(self, params: list[TestCaseParams]) -> str:
lines = []
for param in params:
value = getattr(self.test_case, param.value)
if value is None:
continue
if isinstance(value, list):
value = "\n".join(f" - {item}" for item in value)
lines.append(f"{param.value.upper()}:\n{value}")
if self.labeled_outputs:
for label, value in self.labeled_outputs.items():
if isinstance(value, list):
value = "\n".join(f" - {item}" for item in value)
lines.append(f"{label.upper()}:\n{value}")
return "\n\n".join(lines)
# ---------------------------------------------------------------------------
# VerdictNode
# ---------------------------------------------------------------------------
@dataclass
class VerdictNode:
"""Terminal leaf that returns a score or delegates to a child metric/node."""
verdict: Union[bool, str]
score: int | None = None # Integer 0–10; normalized to 0.0–1.0
child: Union["_AnyNonVerdict", "BaseMetric", None] = None
def __post_init__(self) -> None:
if self.score is None and self.child is None:
raise ValueError("VerdictNode requires either 'score' or 'child'.")
if self.score is not None and self.child is not None:
raise ValueError("VerdictNode cannot have both 'score' and 'child'.")
if self.score is not None and not (0 <= self.score <= 10):
raise ValueError("VerdictNode score must be an integer between 0 and 10.")
async def evaluate(self, ctx: TraversalContext, llm: "BaseLLM") -> float:
if self.score is not None:
return self.score / 10.0
# Delegate to child node or metric
from minival.metrics.base import BaseMetric
if isinstance(self.child, BaseMetric):
return await self.child.a_measure(ctx.test_case)
# Child is another DAG node — continue traversal
return await self.child.evaluate(ctx, llm)
# ---------------------------------------------------------------------------
# TaskNode
# ---------------------------------------------------------------------------
@dataclass
class TaskNode:
"""Extracts or transforms data via an LLM call; passes result to children."""
instructions: str
evaluation_params: list[TestCaseParams]
output_label: str
children: list[Union["TaskNode", "BinaryJudgeNode", "NonBinaryJudgeNode"]]
def _build_prompt(self, ctx: TraversalContext) -> str:
context_section = ctx.build_context_section(self.evaluation_params)
return (
f"{self.instructions}\n\n"
f"Context:\n{context_section}\n\n"
f'Return your result as JSON with a single key "{self.output_label}" '
f"whose value is the extracted/transformed content."
)
async def evaluate(self, ctx: TraversalContext, llm: "BaseLLM") -> float:
prompt = self._build_prompt(ctx)
raw = await llm.a_generate(prompt)
parsed = _parse_json_lenient(raw)
ctx.labeled_outputs[self.output_label] = parsed.get(self.output_label, parsed)
import asyncio
tasks = [child.evaluate(ctx.fork(), llm) for child in self.children]
scores = await asyncio.gather(*tasks)
return sum(scores) / len(scores) if scores else 0.0
# ---------------------------------------------------------------------------
# BinaryJudgeNode
# ---------------------------------------------------------------------------
@dataclass
class BinaryJudgeNode:
"""Evaluates a yes/no criterion; routes to True or False VerdictNode child."""
criteria: str
children: list[VerdictNode] # Exactly two: one verdict=True, one verdict=False
def __post_init__(self) -> None:
verdicts = {c.verdict for c in self.children}
if verdicts != {True, False}:
raise ValueError(
"BinaryJudgeNode must have exactly two VerdictNode children: "
"one with verdict=True and one with verdict=False."
)
def _build_prompt(self, ctx: TraversalContext) -> str:
context_section = ctx.build_context_section(
[p for p in TestCaseParams]
)
return (
f"Evaluate the following criteria:\n{self.criteria}\n\n"
f"Context:\n{context_section}\n\n"
'Return your answer as JSON: {"verdict": true or false, "reason": "..."}'
)
async def evaluate(self, ctx: TraversalContext, llm: "BaseLLM") -> float:
prompt = self._build_prompt(ctx)
raw = await llm.a_generate(prompt)
parsed = _parse_json_lenient(raw)
verdict_raw = parsed.get("verdict", False)
verdict_value = _coerce_bool(verdict_raw)
if verdict_value is None:
verdict_value = False
for child in self.children:
if child.verdict is verdict_value:
return await child.evaluate(ctx, llm)
# Fallback: first child
return await self.children[0].evaluate(ctx, llm)
# ---------------------------------------------------------------------------
# NonBinaryJudgeNode
# ---------------------------------------------------------------------------
@dataclass
class NonBinaryJudgeNode:
"""Selects one option from a categorical set; routes to matching VerdictNode."""
criteria: str
children: list[VerdictNode] # Two or more, each with a distinct string verdict
def __post_init__(self) -> None:
if len(self.children) < 2:
raise ValueError("NonBinaryJudgeNode requires at least two VerdictNode children.")
verdicts = [c.verdict for c in self.children]
if len(verdicts) != len(set(verdicts)):
raise ValueError("NonBinaryJudgeNode children must have distinct verdict strings.")
def _build_prompt(self, ctx: TraversalContext) -> str:
context_section = ctx.build_context_section(
[p for p in TestCaseParams]
)
options = [str(c.verdict) for c in self.children]
options_str = ", ".join(f'"{v}"' for v in options)
return (
f"Evaluate the following criteria:\n{self.criteria}\n\n"
f"Context:\n{context_section}\n\n"
f"Select exactly one of these verdicts: {options_str}\n\n"
f'Return your answer as JSON: {{"verdict": <one of the options above>, "reason": "..."}}'
)
async def evaluate(self, ctx: TraversalContext, llm: "BaseLLM") -> float:
prompt = self._build_prompt(ctx)
raw = await llm.a_generate(prompt)
parsed = _parse_json_lenient(raw)
verdict_value = str(parsed.get("verdict", ""))
for child in self.children:
if str(child.verdict) == verdict_value:
return await child.evaluate(ctx, llm)
# Fallback: first child
return await self.children[0].evaluate(ctx, llm)
_AnyNonVerdict = Union[TaskNode, BinaryJudgeNode, NonBinaryJudgeNode]