chore: import upstream snapshot with attribution
tools_continuous_delivery / Private PyPI non-main branch release (push) Has been skipped
tools_continuous_delivery / Private PyPI main branch release (push) Failing after 2m42s
Publish Promptflow Doc / Build (push) Has been cancelled
Publish Promptflow Doc / Deploy (push) Has been cancelled
Flake8 Lint / flake8 (push) Has been cancelled
Spell check CI / Spell_Check (push) Has been cancelled
tools_continuous_delivery / Private PyPI non-main branch release (push) Has been skipped
tools_continuous_delivery / Private PyPI main branch release (push) Failing after 2m42s
Publish Promptflow Doc / Build (push) Has been cancelled
Publish Promptflow Doc / Deploy (push) Has been cancelled
Flake8 Lint / flake8 (push) Has been cancelled
Spell check CI / Spell_Check (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
from typing import Dict, List
|
||||
|
||||
|
||||
def aggregate(grades: List[str]) -> Dict[str, float]:
|
||||
accuracy = round((grades.count("Correct") / len(grades)), 2) if grades else 0.0
|
||||
return {"accuracy": accuracy}
|
||||
@@ -0,0 +1,3 @@
|
||||
{"groundtruth": "App","prediction": "App"}
|
||||
{"groundtruth": "Channel","prediction": "Channel"}
|
||||
{"groundtruth": "Academic","prediction": "Academic"}
|
||||
@@ -0,0 +1,54 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvalResult:
|
||||
per_row_outputs: List[Any]
|
||||
metrics: Dict[str, Any]
|
||||
errors: List[tuple] = field(default_factory=list)
|
||||
|
||||
|
||||
class EvalRunner:
|
||||
def __init__(self, workflow_factory: Callable[[], Any], aggregate_fn: Callable[..., dict],
|
||||
concurrency: int = 5, input_mapping: Optional[Dict[str, str]] = None):
|
||||
self._workflow_factory = workflow_factory
|
||||
self._aggregate_fn = aggregate_fn
|
||||
self._concurrency = concurrency
|
||||
self._input_mapping = input_mapping
|
||||
|
||||
async def run(self, dataset: List[Any]) -> EvalResult:
|
||||
semaphore = asyncio.Semaphore(self._concurrency)
|
||||
per_row_outputs: List[Any] = [None] * len(dataset)
|
||||
errors: List[tuple] = []
|
||||
|
||||
async def _run_row(index: int, row: Any) -> None:
|
||||
async with semaphore:
|
||||
wf = self._workflow_factory()
|
||||
result = await wf.run(row)
|
||||
per_row_outputs[index] = result.get_outputs()[0]
|
||||
|
||||
tasks = [_run_row(i, row) for i, row in enumerate(dataset)]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
succeeded_outputs: List[Any] = []
|
||||
for i, r in enumerate(results):
|
||||
if isinstance(r, Exception):
|
||||
errors.append((i, r))
|
||||
else:
|
||||
succeeded_outputs.append(per_row_outputs[i])
|
||||
|
||||
aggregation_inputs = self._transpose(succeeded_outputs)
|
||||
if self._input_mapping:
|
||||
aggregation_inputs = {self._input_mapping.get(k, k): v for k, v in aggregation_inputs.items()}
|
||||
metrics = self._aggregate_fn(**aggregation_inputs)
|
||||
return EvalResult(per_row_outputs=succeeded_outputs, metrics=metrics, errors=errors)
|
||||
|
||||
@staticmethod
|
||||
def _transpose(outputs: List[Any]) -> Dict[str, Any]:
|
||||
if not outputs:
|
||||
return {"values": []}
|
||||
if not isinstance(outputs[0], dict):
|
||||
return {"values": outputs}
|
||||
keys = outputs[0].keys()
|
||||
return {k: [o[k] for o in outputs] for k in keys}
|
||||
@@ -0,0 +1 @@
|
||||
agent-framework>=1.0.1
|
||||
@@ -0,0 +1,45 @@
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from aggregation import aggregate
|
||||
from eval_runner import EvalRunner
|
||||
from workflow import EvalInput, create_workflow
|
||||
|
||||
DEFAULT_DATA = Path(__file__).parent / "data.jsonl"
|
||||
|
||||
|
||||
def load_dataset(path: Path) -> list[EvalInput]:
|
||||
rows = []
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line:
|
||||
obj = json.loads(line)
|
||||
rows.append(EvalInput(groundtruth=obj["groundtruth"], prediction=obj["prediction"]))
|
||||
return rows
|
||||
|
||||
|
||||
async def main(data_path: Path, concurrency: int):
|
||||
dataset = load_dataset(data_path)
|
||||
print(f"Loaded {len(dataset)} rows from {data_path}")
|
||||
|
||||
runner = EvalRunner(
|
||||
workflow_factory=create_workflow,
|
||||
aggregate_fn=aggregate,
|
||||
concurrency=concurrency,
|
||||
input_mapping={"values": "grades"},
|
||||
)
|
||||
result = await runner.run(dataset)
|
||||
|
||||
print("\n--- Metrics ---")
|
||||
for key, value in result.metrics.items():
|
||||
print(f" {key}: {value}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--data", type=Path, default=DEFAULT_DATA)
|
||||
parser.add_argument("--concurrency", type=int, default=5)
|
||||
args = parser.parse_args()
|
||||
asyncio.run(main(args.data, args.concurrency))
|
||||
@@ -0,0 +1,65 @@
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from aggregation import aggregate
|
||||
from eval_runner import EvalRunner
|
||||
from workflow import EvalInput, create_workflow
|
||||
|
||||
|
||||
async def test_correct():
|
||||
wf = create_workflow()
|
||||
result = await wf.run(EvalInput(groundtruth="APP", prediction="APP"))
|
||||
assert result.get_outputs()[0] == "Correct"
|
||||
print("PASS: test_correct")
|
||||
|
||||
|
||||
async def test_incorrect():
|
||||
wf = create_workflow()
|
||||
result = await wf.run(EvalInput(groundtruth="APP", prediction="WEB"))
|
||||
assert result.get_outputs()[0] == "Incorrect"
|
||||
print("PASS: test_incorrect")
|
||||
|
||||
|
||||
async def test_batch():
|
||||
dataset = [
|
||||
EvalInput(groundtruth="APP", prediction="APP"),
|
||||
EvalInput(groundtruth="Channel", prediction="Channel"),
|
||||
EvalInput(groundtruth="Academic", prediction="Finance"),
|
||||
]
|
||||
runner = EvalRunner(
|
||||
workflow_factory=create_workflow,
|
||||
aggregate_fn=aggregate,
|
||||
concurrency=5,
|
||||
input_mapping={"values": "grades"},
|
||||
)
|
||||
result = await runner.run(dataset)
|
||||
assert result.metrics["accuracy"] == 0.67
|
||||
print("PASS: test_batch")
|
||||
|
||||
|
||||
async def test_data_jsonl():
|
||||
"""Run eval on every row in data.jsonl"""
|
||||
data_path = Path(__file__).parent / "data.jsonl"
|
||||
rows = [json.loads(line) for line in data_path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
wf = create_workflow()
|
||||
for i, row in enumerate(rows):
|
||||
result = await wf.run(EvalInput(
|
||||
groundtruth=row["groundtruth"],
|
||||
prediction=row["prediction"],
|
||||
))
|
||||
grade = result.get_outputs()[0]
|
||||
assert grade in ("Correct", "Incorrect"), f"Row {i}: unexpected grade '{grade}'"
|
||||
print(f" Row {i}: grade={grade}")
|
||||
print(f"PASS: test_data_jsonl ({len(rows)} rows)")
|
||||
|
||||
|
||||
async def main():
|
||||
await test_correct()
|
||||
await test_incorrect()
|
||||
await test_batch()
|
||||
await test_data_jsonl()
|
||||
print("\nAll tests passed!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,21 @@
|
||||
from dataclasses import dataclass
|
||||
from typing_extensions import Never
|
||||
from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvalInput:
|
||||
groundtruth: str
|
||||
prediction: str
|
||||
|
||||
|
||||
class GradeExecutor(Executor):
|
||||
@handler
|
||||
async def grade(self, input: EvalInput, ctx: WorkflowContext[Never, str]) -> None:
|
||||
result = "Correct" if input.groundtruth.lower() == input.prediction.lower() else "Incorrect"
|
||||
await ctx.yield_output(result)
|
||||
|
||||
|
||||
def create_workflow():
|
||||
_grade = GradeExecutor(id="grade")
|
||||
return WorkflowBuilder(name="EvalClassificationAccuracyRow", start_executor=_grade).build()
|
||||
Reference in New Issue
Block a user