pytest-agent-bdd 0.1.0.dev1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pytest_agent_bdd/__init__.py +45 -0
- pytest_agent_bdd/adapters.py +98 -0
- pytest_agent_bdd/assertions.py +78 -0
- pytest_agent_bdd/integrations/__init__.py +57 -0
- pytest_agent_bdd/integrations/_dependencies.py +22 -0
- pytest_agent_bdd/integrations/langgraph.py +63 -0
- pytest_agent_bdd/judges/__init__.py +93 -0
- pytest_agent_bdd/models.py +90 -0
- pytest_agent_bdd/plugin.py +160 -0
- pytest_agent_bdd/steps.py +192 -0
- pytest_agent_bdd/validation/__init__.py +169 -0
- pytest_agent_bdd/validation/metrics.py +68 -0
- pytest_agent_bdd/validation/robustness.py +95 -0
- pytest_agent_bdd-0.1.0.dev1.dist-info/METADATA +256 -0
- pytest_agent_bdd-0.1.0.dev1.dist-info/RECORD +18 -0
- pytest_agent_bdd-0.1.0.dev1.dist-info/WHEEL +4 -0
- pytest_agent_bdd-0.1.0.dev1.dist-info/entry_points.txt +3 -0
- pytest_agent_bdd-0.1.0.dev1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""pytest-agent-bdd: behavioral acceptance testing for AI agents with Gherkin and pytest."""
|
|
2
|
+
|
|
3
|
+
from .adapters import AgentAdapter, CallableAdapter, ToolRecorder, as_adapter
|
|
4
|
+
from .assertions import (
|
|
5
|
+
AgentBehaviorError,
|
|
6
|
+
AgentExecutionError,
|
|
7
|
+
assert_called_before,
|
|
8
|
+
assert_execution_succeeded,
|
|
9
|
+
assert_no_tool_errors,
|
|
10
|
+
assert_output_mentions,
|
|
11
|
+
assert_tool_called,
|
|
12
|
+
assert_tool_not_called,
|
|
13
|
+
)
|
|
14
|
+
from .judges import Judge, JudgeContractError, check_judgment, get_judge, run_judge
|
|
15
|
+
from .models import AgentExecution, Judgment, ToolCall
|
|
16
|
+
from .validation import JudgeTestCase, JudgeValidationReport, load_dataset, validate_judge
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0.dev0"
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"AgentAdapter",
|
|
22
|
+
"AgentBehaviorError",
|
|
23
|
+
"AgentExecution",
|
|
24
|
+
"AgentExecutionError",
|
|
25
|
+
"CallableAdapter",
|
|
26
|
+
"Judge",
|
|
27
|
+
"JudgeContractError",
|
|
28
|
+
"JudgeTestCase",
|
|
29
|
+
"JudgeValidationReport",
|
|
30
|
+
"Judgment",
|
|
31
|
+
"ToolCall",
|
|
32
|
+
"ToolRecorder",
|
|
33
|
+
"as_adapter",
|
|
34
|
+
"assert_called_before",
|
|
35
|
+
"assert_execution_succeeded",
|
|
36
|
+
"assert_no_tool_errors",
|
|
37
|
+
"assert_output_mentions",
|
|
38
|
+
"assert_tool_called",
|
|
39
|
+
"assert_tool_not_called",
|
|
40
|
+
"check_judgment",
|
|
41
|
+
"get_judge",
|
|
42
|
+
"load_dataset",
|
|
43
|
+
"run_judge",
|
|
44
|
+
"validate_judge",
|
|
45
|
+
]
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""The adapter contract: the only boundary between the plugin and an agent framework."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any, Protocol, runtime_checkable
|
|
8
|
+
|
|
9
|
+
from .models import COMPLETED, FAILED, AgentExecution, ToolCall
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@runtime_checkable
|
|
13
|
+
class AgentAdapter(Protocol):
|
|
14
|
+
"""Runs an agent and returns a normalized :class:`AgentExecution`.
|
|
15
|
+
|
|
16
|
+
Implementations must not raise for agent-side failures: they report them
|
|
17
|
+
through ``AgentExecution.status`` and ``AgentExecution.error`` so that an
|
|
18
|
+
agent failure is never confused with a failed assertion.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def run(self, input: Any) -> AgentExecution: ...
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ToolRecorder:
|
|
25
|
+
"""Helper given to plain-Python agents so they can report tool usage."""
|
|
26
|
+
|
|
27
|
+
def __init__(self) -> None:
|
|
28
|
+
self.calls: list[ToolCall] = []
|
|
29
|
+
self.trace: list[dict[str, Any]] = []
|
|
30
|
+
|
|
31
|
+
def call(self, name: str, func: Callable[..., Any], /, **arguments: Any) -> Any:
|
|
32
|
+
"""Invoke ``func(**arguments)`` and record it as tool ``name``."""
|
|
33
|
+
try:
|
|
34
|
+
result = func(**arguments)
|
|
35
|
+
except Exception as exc: # the agent decides how to handle tool errors
|
|
36
|
+
self.calls.append(ToolCall(name, dict(arguments), None, f"{type(exc).__name__}: {exc}"))
|
|
37
|
+
self.event("tool_error", tool=name, error=str(exc))
|
|
38
|
+
raise
|
|
39
|
+
self.calls.append(ToolCall(name, dict(arguments), result))
|
|
40
|
+
self.event("tool_call", tool=name, arguments=arguments)
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
def record(self, name: str, result: Any = None, **arguments: Any) -> None:
|
|
44
|
+
"""Record a tool call that was executed elsewhere."""
|
|
45
|
+
self.calls.append(ToolCall(name, dict(arguments), result))
|
|
46
|
+
self.event("tool_call", tool=name, arguments=arguments)
|
|
47
|
+
|
|
48
|
+
def event(self, kind: str, **data: Any) -> None:
|
|
49
|
+
self.trace.append({"event": kind, "t": time.monotonic(), **data})
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class CallableAdapter:
|
|
53
|
+
"""Adapter for custom Python agents.
|
|
54
|
+
|
|
55
|
+
Wraps ``agent(input, tools: ToolRecorder) -> output``. If ``state`` is
|
|
56
|
+
given, it is called after the run to capture the agent's final state.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
agent: Callable[[Any, ToolRecorder], Any],
|
|
62
|
+
state: Callable[[], Any] | None = None,
|
|
63
|
+
) -> None:
|
|
64
|
+
self._agent = agent
|
|
65
|
+
self._state = state
|
|
66
|
+
|
|
67
|
+
def run(self, input: Any) -> AgentExecution:
|
|
68
|
+
recorder = ToolRecorder()
|
|
69
|
+
initial_state = self._state() if self._state else None
|
|
70
|
+
recorder.event("run_started")
|
|
71
|
+
try:
|
|
72
|
+
output = self._agent(input, recorder)
|
|
73
|
+
status, error = COMPLETED, None
|
|
74
|
+
except Exception as exc:
|
|
75
|
+
output, status, error = None, FAILED, exc
|
|
76
|
+
recorder.event("run_finished", status=status)
|
|
77
|
+
return AgentExecution(
|
|
78
|
+
input=input,
|
|
79
|
+
output=output,
|
|
80
|
+
tool_calls=recorder.calls,
|
|
81
|
+
trace=recorder.trace,
|
|
82
|
+
initial_state=initial_state,
|
|
83
|
+
final_state=self._state() if self._state else None,
|
|
84
|
+
status=status,
|
|
85
|
+
error=error,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def as_adapter(obj: Any) -> AgentAdapter:
|
|
90
|
+
"""Accept either an adapter or a plain callable agent."""
|
|
91
|
+
if isinstance(obj, AgentAdapter):
|
|
92
|
+
return obj
|
|
93
|
+
if callable(obj):
|
|
94
|
+
return CallableAdapter(obj)
|
|
95
|
+
raise TypeError(
|
|
96
|
+
f"{type(obj).__name__} is neither an AgentAdapter (with run(input) -> AgentExecution) "
|
|
97
|
+
"nor a callable agent(input, tools)."
|
|
98
|
+
)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Assertion helpers with standardized, diagnostic failure messages."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .models import AgentExecution
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AgentBehaviorError(AssertionError):
|
|
11
|
+
"""The agent ran, but did not behave as the contract requires."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, message: str, execution: AgentExecution | None = None) -> None:
|
|
14
|
+
details = f"\n\n--- agent execution ---\n{execution.summary()}" if execution else ""
|
|
15
|
+
super().__init__(message + details)
|
|
16
|
+
self.execution = execution
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AgentExecutionError(AssertionError):
|
|
20
|
+
"""The agent itself failed, so behavioral assertions are not meaningful."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def assert_execution_succeeded(execution: AgentExecution) -> None:
|
|
24
|
+
if not execution.succeeded:
|
|
25
|
+
raise AgentExecutionError(
|
|
26
|
+
"Agent execution did not complete; behavioral assertions were not evaluated."
|
|
27
|
+
f"\n\n--- agent execution ---\n{execution.summary()}"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def assert_tool_called(execution: AgentExecution, name: str, **expected_args: Any) -> None:
|
|
32
|
+
assert_execution_succeeded(execution)
|
|
33
|
+
calls = execution.calls_to(name)
|
|
34
|
+
if not calls:
|
|
35
|
+
raise AgentBehaviorError(f"Expected tool '{name}' to be called, but it was not.", execution)
|
|
36
|
+
if expected_args and not any(_args_match(c.arguments, expected_args) for c in calls):
|
|
37
|
+
raise AgentBehaviorError(
|
|
38
|
+
f"Tool '{name}' was called, but never with arguments matching {expected_args}.",
|
|
39
|
+
execution,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def assert_tool_not_called(execution: AgentExecution, name: str) -> None:
|
|
44
|
+
assert_execution_succeeded(execution)
|
|
45
|
+
if execution.calls_to(name):
|
|
46
|
+
raise AgentBehaviorError(f"Expected tool '{name}' NOT to be called, but it was.", execution)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def assert_called_before(execution: AgentExecution, first: str, second: str) -> None:
|
|
50
|
+
assert_execution_succeeded(execution)
|
|
51
|
+
names = execution.tool_names
|
|
52
|
+
for tool in (first, second):
|
|
53
|
+
if tool not in names:
|
|
54
|
+
raise AgentBehaviorError(f"Tool '{tool}' was never called.", execution)
|
|
55
|
+
if names.index(first) > names.index(second):
|
|
56
|
+
raise AgentBehaviorError(f"Expected '{first}' to be called before '{second}'.", execution)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def assert_no_tool_errors(execution: AgentExecution) -> None:
|
|
60
|
+
failed = [c for c in execution.tool_calls if c.error]
|
|
61
|
+
if failed:
|
|
62
|
+
names = ", ".join(c.name for c in failed)
|
|
63
|
+
raise AgentBehaviorError(f"Tool calls reported errors: {names}.", execution)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def assert_output_mentions(execution: AgentExecution, text: str) -> None:
|
|
67
|
+
assert_execution_succeeded(execution)
|
|
68
|
+
if text.lower() not in str(execution.output).lower():
|
|
69
|
+
raise AgentBehaviorError(f"Expected the response to mention '{text}'.", execution)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _args_match(actual: dict[str, Any], expected: dict[str, Any]) -> bool:
|
|
73
|
+
for key, value in expected.items():
|
|
74
|
+
if key not in actual:
|
|
75
|
+
return False
|
|
76
|
+
if actual[key] != value and str(actual[key]) != str(value):
|
|
77
|
+
return False
|
|
78
|
+
return True
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Lazy loading and discovery of agent-framework integrations.
|
|
2
|
+
|
|
3
|
+
Four separate responsibilities, deliberately kept apart:
|
|
4
|
+
|
|
5
|
+
* dependency detection -- is the framework installed? (_dependencies)
|
|
6
|
+
* integration discovery -- is an adapter available? (discover_integrations)
|
|
7
|
+
* integration selection -- which one does the test want? (ini option / fixture)
|
|
8
|
+
* agent initialization -- which agent instance to run? (agent_under_test fixture)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from importlib import import_module
|
|
14
|
+
from importlib.metadata import entry_points
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from ._dependencies import MissingIntegrationError, require_dependency
|
|
18
|
+
|
|
19
|
+
ENTRY_POINT_GROUP = "pytest_agent_bdd.integrations"
|
|
20
|
+
|
|
21
|
+
# First-party integrations: name -> (module, class). Imported only on request.
|
|
22
|
+
BUILTIN_INTEGRATIONS: dict[str, tuple[str, str]] = {
|
|
23
|
+
"langgraph": ("pytest_agent_bdd.integrations.langgraph", "LangGraphAdapter"),
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def discover_integrations() -> dict[str, Any]:
|
|
28
|
+
"""Return third-party adapters registered through entry points (not loaded)."""
|
|
29
|
+
return {ep.name: ep for ep in entry_points(group=ENTRY_POINT_GROUP)}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def available_integrations() -> list[str]:
|
|
33
|
+
return sorted(set(BUILTIN_INTEGRATIONS) | set(discover_integrations()))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load_adapter(name: str) -> type:
|
|
37
|
+
"""Import and return the adapter class for integration ``name``."""
|
|
38
|
+
if name in BUILTIN_INTEGRATIONS:
|
|
39
|
+
module_name, class_name = BUILTIN_INTEGRATIONS[name]
|
|
40
|
+
return getattr(import_module(module_name), class_name)
|
|
41
|
+
third_party = discover_integrations()
|
|
42
|
+
if name in third_party:
|
|
43
|
+
return third_party[name].load()
|
|
44
|
+
raise ValueError(
|
|
45
|
+
f"Unknown integration: {name!r}. Available: {', '.join(available_integrations()) or 'none'}"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"BUILTIN_INTEGRATIONS",
|
|
51
|
+
"ENTRY_POINT_GROUP",
|
|
52
|
+
"MissingIntegrationError",
|
|
53
|
+
"available_integrations",
|
|
54
|
+
"discover_integrations",
|
|
55
|
+
"load_adapter",
|
|
56
|
+
"require_dependency",
|
|
57
|
+
]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Optional-dependency detection, without importing the dependency."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib.util import find_spec
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MissingIntegrationError(ImportError):
|
|
9
|
+
"""An integration was requested but its optional dependency is not installed."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def require_dependency(module_name: str, extra_name: str) -> None:
|
|
13
|
+
"""Raise an actionable error if ``module_name`` cannot be imported.
|
|
14
|
+
|
|
15
|
+
``module_name`` is the import name and ``extra_name`` the pip extra; they
|
|
16
|
+
are kept separate because import and distribution names can differ.
|
|
17
|
+
"""
|
|
18
|
+
if find_spec(module_name) is None:
|
|
19
|
+
raise MissingIntegrationError(
|
|
20
|
+
f"This integration requires '{module_name}'. "
|
|
21
|
+
f"Install it with: pip install 'pytest-agent-bdd[{extra_name}]'"
|
|
22
|
+
)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""LangGraph integration (first-party, installed with the ``langgraph`` extra).
|
|
2
|
+
|
|
3
|
+
Status: skeleton. Tool-call extraction from LangGraph message state is a
|
|
4
|
+
first implementation; trace capture via callbacks/streaming is still TODO.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from ._dependencies import require_dependency
|
|
12
|
+
|
|
13
|
+
require_dependency("langgraph", "langgraph")
|
|
14
|
+
|
|
15
|
+
from ..models import COMPLETED, FAILED, AgentExecution, ToolCall # noqa: E402
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class LangGraphAdapter:
|
|
19
|
+
"""Run a compiled LangGraph graph and normalize its result."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, graph: Any, input_key: str = "messages") -> None:
|
|
22
|
+
self.graph = graph
|
|
23
|
+
self.input_key = input_key
|
|
24
|
+
|
|
25
|
+
def run(self, input: Any) -> AgentExecution:
|
|
26
|
+
payload = input if isinstance(input, dict) else {self.input_key: [("user", str(input))]}
|
|
27
|
+
trace: list[dict[str, Any]] = []
|
|
28
|
+
try:
|
|
29
|
+
# TODO: use graph.stream(..., stream_mode="updates") to capture node-level trace.
|
|
30
|
+
state = self.graph.invoke(payload)
|
|
31
|
+
status, error = COMPLETED, None
|
|
32
|
+
except Exception as exc:
|
|
33
|
+
state, status, error = None, FAILED, exc
|
|
34
|
+
return AgentExecution(
|
|
35
|
+
input=input,
|
|
36
|
+
output=_final_text(state),
|
|
37
|
+
tool_calls=_tool_calls(state),
|
|
38
|
+
trace=trace,
|
|
39
|
+
final_state=state,
|
|
40
|
+
status=status,
|
|
41
|
+
error=error,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _messages(state: Any) -> list[Any]:
|
|
46
|
+
if isinstance(state, dict):
|
|
47
|
+
return list(state.get("messages", []))
|
|
48
|
+
return []
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _final_text(state: Any) -> Any:
|
|
52
|
+
messages = _messages(state)
|
|
53
|
+
if not messages:
|
|
54
|
+
return state
|
|
55
|
+
return getattr(messages[-1], "content", messages[-1])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _tool_calls(state: Any) -> list[ToolCall]:
|
|
59
|
+
calls = []
|
|
60
|
+
for message in _messages(state):
|
|
61
|
+
for call in getattr(message, "tool_calls", None) or []:
|
|
62
|
+
calls.append(ToolCall(name=call.get("name", "?"), arguments=call.get("args", {})))
|
|
63
|
+
return calls
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Pluggable judges: any object with ``evaluate(...) -> Judgment``.
|
|
2
|
+
|
|
3
|
+
The plugin never assumes a judge is an LLM. It may be a Python function, an
|
|
4
|
+
external service, a human workflow, or an LLM -- all behind the same contract.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from typing import Any, Protocol, runtime_checkable
|
|
11
|
+
|
|
12
|
+
from ..models import Judgment
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@runtime_checkable
|
|
16
|
+
class Judge(Protocol):
|
|
17
|
+
def evaluate(
|
|
18
|
+
self,
|
|
19
|
+
*,
|
|
20
|
+
input: str,
|
|
21
|
+
actual: str,
|
|
22
|
+
expected: str,
|
|
23
|
+
context: dict[str, Any] | None = None,
|
|
24
|
+
) -> Judgment: ...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class JudgeContractError(AssertionError):
|
|
28
|
+
"""The judge misbehaved as software (as opposed to judging badly)."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_judge(judges: dict[str, Any], name: str) -> Judge:
|
|
32
|
+
if name not in judges:
|
|
33
|
+
raise JudgeContractError(
|
|
34
|
+
f"Judge '{name}' is not registered. Available judges: {sorted(judges) or 'none'}. "
|
|
35
|
+
"Register judges by overriding the `judges` fixture in conftest.py."
|
|
36
|
+
)
|
|
37
|
+
judge = judges[name]
|
|
38
|
+
if not isinstance(judge, Judge):
|
|
39
|
+
raise JudgeContractError(
|
|
40
|
+
f"Judge '{name}' has no evaluate(*, input, actual, expected) method."
|
|
41
|
+
)
|
|
42
|
+
return judge
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def check_judgment(judgment: Any, judge_name: str = "judge") -> Judgment:
|
|
46
|
+
"""Contract test applied to every judgment: reject malformed results."""
|
|
47
|
+
if not isinstance(judgment, Judgment):
|
|
48
|
+
raise JudgeContractError(
|
|
49
|
+
f"{judge_name} returned {type(judgment).__name__}, expected pytest_agent_bdd.Judgment."
|
|
50
|
+
)
|
|
51
|
+
if not isinstance(judgment.passed, bool):
|
|
52
|
+
raise JudgeContractError(f"{judge_name}: 'passed' must be a bool, got {judgment.passed!r}.")
|
|
53
|
+
if not _unit_interval(judgment.score):
|
|
54
|
+
raise JudgeContractError(
|
|
55
|
+
f"{judge_name}: 'score' must be within [0, 1], got {judgment.score!r}."
|
|
56
|
+
)
|
|
57
|
+
if judgment.confidence is not None and not _unit_interval(judgment.confidence):
|
|
58
|
+
raise JudgeContractError(
|
|
59
|
+
f"{judge_name}: 'confidence' must be None or within [0, 1], "
|
|
60
|
+
f"got {judgment.confidence!r}."
|
|
61
|
+
)
|
|
62
|
+
if not isinstance(judgment.reason, str) or not judgment.reason.strip():
|
|
63
|
+
raise JudgeContractError(f"{judge_name}: 'reason' must be a non-empty string.")
|
|
64
|
+
return judgment
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def run_judge(
|
|
68
|
+
judge: Judge,
|
|
69
|
+
*,
|
|
70
|
+
input: str,
|
|
71
|
+
actual: str,
|
|
72
|
+
expected: str,
|
|
73
|
+
context: dict[str, Any] | None = None,
|
|
74
|
+
judge_name: str = "judge",
|
|
75
|
+
) -> Judgment:
|
|
76
|
+
"""Evaluate and enforce the judge contract on the result."""
|
|
77
|
+
try:
|
|
78
|
+
result = judge.evaluate(input=input, actual=actual, expected=expected, context=context)
|
|
79
|
+
except Exception as exc:
|
|
80
|
+
raise JudgeContractError(f"{judge_name} raised {type(exc).__name__}: {exc}") from exc
|
|
81
|
+
return check_judgment(result, judge_name)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _unit_interval(value: Any) -> bool:
|
|
85
|
+
return (
|
|
86
|
+
isinstance(value, (int, float))
|
|
87
|
+
and not isinstance(value, bool)
|
|
88
|
+
and not math.isnan(value)
|
|
89
|
+
and 0.0 <= value <= 1.0
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
__all__ = ["Judge", "JudgeContractError", "check_judgment", "get_judge", "run_judge"]
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Framework-independent data model for agent executions and judgments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
COMPLETED = "completed"
|
|
10
|
+
FAILED = "failed"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class ToolCall:
|
|
15
|
+
"""One tool invocation observed during an agent execution."""
|
|
16
|
+
|
|
17
|
+
name: str
|
|
18
|
+
arguments: dict[str, Any] = field(default_factory=dict)
|
|
19
|
+
result: Any = None
|
|
20
|
+
error: str | None = None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class AgentExecution:
|
|
25
|
+
"""Normalized record of a single agent run.
|
|
26
|
+
|
|
27
|
+
Adapters translate framework-specific results into this structure so that
|
|
28
|
+
the same Gherkin scenario can run against any agent framework.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
input: Any
|
|
32
|
+
output: Any = None
|
|
33
|
+
tool_calls: list[ToolCall] = field(default_factory=list)
|
|
34
|
+
trace: list[dict[str, Any]] = field(default_factory=list)
|
|
35
|
+
initial_state: Any = None
|
|
36
|
+
final_state: Any = None
|
|
37
|
+
status: str = COMPLETED
|
|
38
|
+
error: BaseException | None = None
|
|
39
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def succeeded(self) -> bool:
|
|
43
|
+
return self.status == COMPLETED and self.error is None
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def tool_names(self) -> list[str]:
|
|
47
|
+
return [call.name for call in self.tool_calls]
|
|
48
|
+
|
|
49
|
+
def calls_to(self, name: str) -> list[ToolCall]:
|
|
50
|
+
return [call for call in self.tool_calls if call.name == name]
|
|
51
|
+
|
|
52
|
+
def summary(self, max_trace: int = 10) -> str:
|
|
53
|
+
"""Human-readable diagnostic used in assertion failure messages."""
|
|
54
|
+
lines = [
|
|
55
|
+
f"status: {self.status}",
|
|
56
|
+
f"input: {_short(self.input)}",
|
|
57
|
+
f"output: {_short(self.output)}",
|
|
58
|
+
]
|
|
59
|
+
if self.error is not None:
|
|
60
|
+
lines.append(f"error: {type(self.error).__name__}: {self.error}")
|
|
61
|
+
if self.tool_calls:
|
|
62
|
+
lines.append("tool calls:")
|
|
63
|
+
for i, call in enumerate(self.tool_calls, 1):
|
|
64
|
+
suffix = f" -> ERROR {call.error}" if call.error else ""
|
|
65
|
+
lines.append(f" {i}. {call.name}({_short(call.arguments)}){suffix}")
|
|
66
|
+
else:
|
|
67
|
+
lines.append("tool calls: (none)")
|
|
68
|
+
if self.trace:
|
|
69
|
+
lines.append(f"trace (first {min(max_trace, len(self.trace))} of {len(self.trace)}):")
|
|
70
|
+
lines.extend(f" - {_short(event)}" for event in self.trace[:max_trace])
|
|
71
|
+
return "\n".join(lines)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class Judgment:
|
|
76
|
+
"""Normalized result returned by every judge, whatever its implementation."""
|
|
77
|
+
|
|
78
|
+
passed: bool
|
|
79
|
+
score: float
|
|
80
|
+
reason: str
|
|
81
|
+
confidence: float | None = None
|
|
82
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _short(value: Any, limit: int = 200) -> str:
|
|
86
|
+
try:
|
|
87
|
+
text = value if isinstance(value, str) else json.dumps(value, default=str)
|
|
88
|
+
except (TypeError, ValueError):
|
|
89
|
+
text = repr(value)
|
|
90
|
+
return text if len(text) <= limit else text[: limit - 3] + "..."
|