agentx-python 0.4.8__py3-none-any.whl → 0.4.10__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.
- agentx/agentx.py +28 -14
- agentx/evaluations/__init__.py +3 -0
- agentx/evaluations/_term.py +91 -0
- agentx/evaluations/adapters/__init__.py +5 -0
- agentx/evaluations/adapters/http_endpoint.py +69 -0
- agentx/evaluations/adapters/precomputed.py +35 -0
- agentx/evaluations/adapters/raw.py +38 -0
- agentx/evaluations/client.py +202 -0
- agentx/evaluations/datasets.py +235 -0
- agentx/evaluations/models.py +388 -0
- agentx/evaluations/redaction.py +57 -0
- agentx/evaluations/reporting.py +172 -0
- agentx/evaluations/results.py +125 -0
- agentx/evaluations/runner.py +312 -0
- agentx/evaluations/tracing.py +54 -0
- agentx/resources/agent.py +15 -5
- agentx/resources/conversation.py +5 -5
- agentx/resources/workforce.py +9 -7
- agentx/util.py +14 -0
- agentx/version.py +1 -1
- agentx_python-0.4.10.dist-info/METADATA +198 -0
- agentx_python-0.4.10.dist-info/RECORD +27 -0
- {agentx_python-0.4.8.dist-info → agentx_python-0.4.10.dist-info}/WHEEL +1 -1
- agentx_python-0.4.8.dist-info/METADATA +0 -188
- agentx_python-0.4.8.dist-info/RECORD +0 -13
- {agentx_python-0.4.8.dist-info → agentx_python-0.4.10.dist-info}/licenses/LICENSE +0 -0
- {agentx_python-0.4.8.dist-info → agentx_python-0.4.10.dist-info}/top_level.txt +0 -0
agentx/agentx.py
CHANGED
|
@@ -3,37 +3,51 @@ import requests
|
|
|
3
3
|
import os
|
|
4
4
|
import logging
|
|
5
5
|
|
|
6
|
-
from agentx.util import get_headers
|
|
6
|
+
from agentx.util import get_headers, api_base
|
|
7
7
|
from agentx.resources.agent import Agent
|
|
8
8
|
from agentx.resources.workforce import Workforce
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
class AgentX:
|
|
12
12
|
|
|
13
|
-
def __init__(self, api_key: str = None):
|
|
13
|
+
def __init__(self, api_key: str = None, base_url: str = None):
|
|
14
14
|
self.api_key = api_key or os.getenv("AGENTX_API_KEY")
|
|
15
15
|
if self.api_key and not os.getenv("AGENTX_API_KEY"):
|
|
16
16
|
os.environ["AGENTX_API_KEY"] = self.api_key
|
|
17
17
|
|
|
18
|
+
# base_url overrides AGENTX_API_BASE_URL env var (and the SDK default)
|
|
19
|
+
self.base_url = base_url or os.getenv("AGENTX_API_BASE_URL")
|
|
20
|
+
if self.base_url:
|
|
21
|
+
os.environ["AGENTX_API_BASE_URL"] = self.base_url
|
|
22
|
+
|
|
23
|
+
from agentx.evaluations.client import EvaluationsClient
|
|
24
|
+
from agentx.evaluations.runner import EvaluationsRunner
|
|
25
|
+
from agentx.version import VERSION
|
|
26
|
+
|
|
27
|
+
_eval_client = EvaluationsClient(
|
|
28
|
+
api_key=self.api_key,
|
|
29
|
+
sdk_version=VERSION,
|
|
30
|
+
base_url=self.base_url,
|
|
31
|
+
)
|
|
32
|
+
self.evaluations = EvaluationsRunner(_eval_client)
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def from_env(cls) -> "AgentX":
|
|
36
|
+
"""Create an AgentX client using AGENTX_API_KEY (and optionally AGENTX_API_BASE_URL) from the environment."""
|
|
37
|
+
return cls()
|
|
38
|
+
|
|
18
39
|
def get_agent(self, id: str) -> Agent:
|
|
19
|
-
url = f"
|
|
40
|
+
url = f"{api_base()}/access/agents/{id}"
|
|
20
41
|
# Make a GET request to the AgentX API
|
|
21
42
|
response = requests.get(url, headers=get_headers())
|
|
22
43
|
# Check if response was successful
|
|
23
44
|
if response.status_code == 200:
|
|
24
|
-
|
|
25
|
-
return Agent(
|
|
26
|
-
id=agent_res.get("_id"),
|
|
27
|
-
name=agent_res.get("name"),
|
|
28
|
-
avatar=agent_res.get("avatar"),
|
|
29
|
-
createdAt=agent_res.get("createdAt"),
|
|
30
|
-
updatedAt=agent_res.get("updatedAt"),
|
|
31
|
-
)
|
|
45
|
+
return Agent(**response.json())
|
|
32
46
|
else:
|
|
33
47
|
raise Exception(f"Failed to retrieve agent: {response.reason}")
|
|
34
48
|
|
|
35
49
|
def list_agents(self) -> List[Agent]:
|
|
36
|
-
url = "
|
|
50
|
+
url = f"{api_base()}/access/agents"
|
|
37
51
|
# Make a GET request to the AgentX API
|
|
38
52
|
response = requests.get(url, headers=get_headers())
|
|
39
53
|
# Check if response was successful
|
|
@@ -45,7 +59,7 @@ class AgentX:
|
|
|
45
59
|
@staticmethod
|
|
46
60
|
def list_workforces() -> List["Workforce"]:
|
|
47
61
|
"""List all workforces/teams."""
|
|
48
|
-
url = "
|
|
62
|
+
url = f"{api_base()}/access/teams"
|
|
49
63
|
response = requests.get(url, headers=get_headers())
|
|
50
64
|
if response.status_code == 200:
|
|
51
65
|
return [Workforce(**workforce) for workforce in response.json()]
|
|
@@ -56,7 +70,7 @@ class AgentX:
|
|
|
56
70
|
|
|
57
71
|
def get_profile(self):
|
|
58
72
|
"""Get the current user's profile information."""
|
|
59
|
-
url = "
|
|
73
|
+
url = f"{api_base()}/access/getProfile"
|
|
60
74
|
response = requests.get(url, headers=get_headers())
|
|
61
75
|
if response.status_code == 200:
|
|
62
76
|
return response.json()
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Minimal ANSI terminal helpers — no external dependencies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import itertools
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
_IS_TTY = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _c(code: str) -> str:
|
|
14
|
+
return f"\033[{code}m" if _IS_TTY else ""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
RESET = _c("0")
|
|
18
|
+
BOLD = _c("1")
|
|
19
|
+
DIM = _c("2")
|
|
20
|
+
GREEN = _c("32")
|
|
21
|
+
YELLOW = _c("33")
|
|
22
|
+
RED = _c("31")
|
|
23
|
+
CYAN = _c("36")
|
|
24
|
+
MAGENTA = _c("35")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def green(s: str) -> str:
|
|
28
|
+
return f"{GREEN}{s}{RESET}"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def yellow(s: str) -> str:
|
|
32
|
+
return f"{YELLOW}{s}{RESET}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def red(s: str) -> str:
|
|
36
|
+
return f"{RED}{s}{RESET}"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cyan(s: str) -> str:
|
|
40
|
+
return f"{CYAN}{s}{RESET}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def bold(s: str) -> str:
|
|
44
|
+
return f"{BOLD}{s}{RESET}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def dim(s: str) -> str:
|
|
48
|
+
return f"{DIM}{s}{RESET}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def magenta(s: str) -> str:
|
|
52
|
+
return f"{MAGENTA}{s}{RESET}"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Spinner:
|
|
56
|
+
"""Inline spinner that overwrites the current line on a TTY."""
|
|
57
|
+
|
|
58
|
+
_FRAMES = ("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")
|
|
59
|
+
|
|
60
|
+
def __init__(self, message: str):
|
|
61
|
+
self._message = message
|
|
62
|
+
self._stop = threading.Event()
|
|
63
|
+
self._thread: threading.Thread | None = None
|
|
64
|
+
|
|
65
|
+
def __enter__(self) -> "Spinner":
|
|
66
|
+
if not _IS_TTY:
|
|
67
|
+
print(f" {self._message}...", flush=True)
|
|
68
|
+
return self
|
|
69
|
+
self._stop.clear()
|
|
70
|
+
self._thread = threading.Thread(target=self._spin, daemon=True)
|
|
71
|
+
self._thread.start()
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
def __exit__(self, *_) -> None:
|
|
75
|
+
if not _IS_TTY:
|
|
76
|
+
return
|
|
77
|
+
self._stop.set()
|
|
78
|
+
if self._thread:
|
|
79
|
+
self._thread.join()
|
|
80
|
+
sys.stdout.write(f"\r{' ' * (len(self._message) + 12)}\r")
|
|
81
|
+
sys.stdout.flush()
|
|
82
|
+
|
|
83
|
+
def _spin(self) -> None:
|
|
84
|
+
for frame in itertools.cycle(self._FRAMES):
|
|
85
|
+
if self._stop.is_set():
|
|
86
|
+
break
|
|
87
|
+
sys.stdout.write(
|
|
88
|
+
f"\r {CYAN}{frame}{RESET} {self._message} {DIM}(this may take ~60s+){RESET}"
|
|
89
|
+
)
|
|
90
|
+
sys.stdout.flush()
|
|
91
|
+
time.sleep(0.08)
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
from agentx.evaluations.adapters.raw import RawCallableAdapter
|
|
2
|
+
from agentx.evaluations.adapters.precomputed import PrecomputedAdapter
|
|
3
|
+
from agentx.evaluations.adapters.http_endpoint import HttpEndpointAdapter
|
|
4
|
+
|
|
5
|
+
__all__ = ["RawCallableAdapter", "PrecomputedAdapter", "HttpEndpointAdapter"]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from typing import Any, Dict, Optional
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from agentx.evaluations.models import EvaluationCase, EvaluationResult
|
|
9
|
+
from agentx.evaluations.results import normalize_error, normalize_result
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class HttpEndpointAdapter:
|
|
13
|
+
"""
|
|
14
|
+
Calls a user-hosted HTTP endpoint for each evaluation case.
|
|
15
|
+
The SDK (running locally) makes the request — the AgentX API never
|
|
16
|
+
touches the customer's endpoint.
|
|
17
|
+
|
|
18
|
+
The endpoint receives a POST with::
|
|
19
|
+
|
|
20
|
+
{"query": "...", "case_id": "...", "metadata": {...}}
|
|
21
|
+
|
|
22
|
+
It should respond with a JSON body containing at least ``output``
|
|
23
|
+
(or ``text``) and optionally ``trace`` and ``metadata``.
|
|
24
|
+
|
|
25
|
+
Usage::
|
|
26
|
+
|
|
27
|
+
adapter = HttpEndpointAdapter(
|
|
28
|
+
url="http://localhost:8080/eval",
|
|
29
|
+
headers={"Authorization": "Bearer my-token"},
|
|
30
|
+
timeout=30,
|
|
31
|
+
)
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
url: str,
|
|
37
|
+
headers: Optional[Dict[str, str]] = None,
|
|
38
|
+
timeout: int = 30,
|
|
39
|
+
method: str = "POST",
|
|
40
|
+
):
|
|
41
|
+
self._url = url
|
|
42
|
+
self._headers = headers or {}
|
|
43
|
+
self._timeout = timeout
|
|
44
|
+
self._method = method.upper()
|
|
45
|
+
|
|
46
|
+
def run(self, case: EvaluationCase) -> EvaluationResult:
|
|
47
|
+
payload = {
|
|
48
|
+
"query": case.query,
|
|
49
|
+
"case_id": case.case_id,
|
|
50
|
+
"question_index": case.question_index,
|
|
51
|
+
"run_number": case.run_number,
|
|
52
|
+
}
|
|
53
|
+
start = time.monotonic()
|
|
54
|
+
try:
|
|
55
|
+
resp = requests.request(
|
|
56
|
+
self._method,
|
|
57
|
+
self._url,
|
|
58
|
+
json=payload,
|
|
59
|
+
headers=self._headers,
|
|
60
|
+
timeout=self._timeout,
|
|
61
|
+
)
|
|
62
|
+
resp.raise_for_status()
|
|
63
|
+
elapsed = int((time.monotonic() - start) * 1000)
|
|
64
|
+
raw = resp.json()
|
|
65
|
+
except Exception as exc:
|
|
66
|
+
elapsed = int((time.monotonic() - start) * 1000)
|
|
67
|
+
return normalize_error(case, exc, latency_ms=elapsed)
|
|
68
|
+
|
|
69
|
+
return normalize_result(case, raw, latency_ms=elapsed)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, List, Union
|
|
4
|
+
|
|
5
|
+
from agentx.evaluations.models import EvaluationCase, EvaluationResult
|
|
6
|
+
from agentx.evaluations.results import normalize_result
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PrecomputedAdapter:
|
|
10
|
+
"""
|
|
11
|
+
Adapter for pre-computed outputs — useful when you already have agent
|
|
12
|
+
responses and just want AgentX to score them.
|
|
13
|
+
|
|
14
|
+
Accepts a list or dict keyed by case_id::
|
|
15
|
+
|
|
16
|
+
outputs = {
|
|
17
|
+
"case-0": "You can reset your password from account settings.",
|
|
18
|
+
"case-1": {"output": "Contact support@example.com", "metadata": {...}},
|
|
19
|
+
}
|
|
20
|
+
adapter = PrecomputedAdapter(outputs)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, outputs: Union[List[Any], Dict[str, Any]]):
|
|
24
|
+
if isinstance(outputs, list):
|
|
25
|
+
self._lookup: Dict[str, Any] = {str(i): v for i, v in enumerate(outputs)}
|
|
26
|
+
else:
|
|
27
|
+
self._lookup = {str(k): v for k, v in outputs.items()}
|
|
28
|
+
|
|
29
|
+
def run(self, case: EvaluationCase) -> EvaluationResult:
|
|
30
|
+
raw = self._lookup.get(case.case_id) or self._lookup.get(
|
|
31
|
+
str(case.question_index)
|
|
32
|
+
)
|
|
33
|
+
if raw is None:
|
|
34
|
+
raw = ""
|
|
35
|
+
return normalize_result(case, raw, latency_ms=0)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Callable
|
|
4
|
+
|
|
5
|
+
from agentx.evaluations.models import EvaluationCase, EvaluationResult
|
|
6
|
+
from agentx.evaluations.results import normalize_error, normalize_result
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class RawCallableAdapter:
|
|
10
|
+
"""
|
|
11
|
+
Wraps any Python callable that accepts an EvaluationCase and returns
|
|
12
|
+
str | dict | EvaluationResult.
|
|
13
|
+
|
|
14
|
+
Usage::
|
|
15
|
+
|
|
16
|
+
def my_agent(case: EvaluationCase) -> str:
|
|
17
|
+
return my_llm.invoke(case.query)
|
|
18
|
+
|
|
19
|
+
adapter = RawCallableAdapter(my_agent)
|
|
20
|
+
result = adapter.run(case)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, fn: Callable[[EvaluationCase], Any]):
|
|
24
|
+
self._fn = fn
|
|
25
|
+
|
|
26
|
+
def run(
|
|
27
|
+
self, case: EvaluationCase, latency_ms: int | None = None
|
|
28
|
+
) -> EvaluationResult:
|
|
29
|
+
import time
|
|
30
|
+
|
|
31
|
+
start = time.monotonic()
|
|
32
|
+
try:
|
|
33
|
+
raw = self._fn(case)
|
|
34
|
+
except Exception as exc:
|
|
35
|
+
elapsed = int((time.monotonic() - start) * 1000)
|
|
36
|
+
return normalize_error(case, exc, latency_ms=elapsed)
|
|
37
|
+
elapsed = int((time.monotonic() - start) * 1000)
|
|
38
|
+
return normalize_result(case, raw, latency_ms=elapsed)
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
import uuid
|
|
7
|
+
from typing import Any, Dict, List, Optional
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
from agentx.evaluations.models import (
|
|
12
|
+
BatchAppendResponse,
|
|
13
|
+
Dataset,
|
|
14
|
+
EvaluationResult,
|
|
15
|
+
EvaluationRun,
|
|
16
|
+
EvaluationSubject,
|
|
17
|
+
Report,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
from agentx.util import _DEFAULT_API_BASE as _UTIL_API_BASE
|
|
23
|
+
|
|
24
|
+
_DEFAULT_BASE_URL = f"{_UTIL_API_BASE}/custom-agent-evaluations"
|
|
25
|
+
SDK_NAME = "agentx-python"
|
|
26
|
+
|
|
27
|
+
_RETRYABLE_STATUS = {429, 500, 502, 503, 504}
|
|
28
|
+
_MAX_RETRIES = 3
|
|
29
|
+
_RETRY_BACKOFF = [1.0, 2.0, 4.0]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AgentXEvaluationsError(Exception):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class AgentXAuthError(AgentXEvaluationsError):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class AgentXValidationError(AgentXEvaluationsError):
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class EvaluationsClient:
|
|
45
|
+
def __init__(
|
|
46
|
+
self, api_key: str, sdk_version: str = "unknown", base_url: str = None
|
|
47
|
+
):
|
|
48
|
+
if not api_key:
|
|
49
|
+
raise AgentXAuthError("AGENTX_API_KEY is required")
|
|
50
|
+
self._api_key = api_key
|
|
51
|
+
self._sdk_version = sdk_version
|
|
52
|
+
# Priority: constructor arg > env var > SDK default
|
|
53
|
+
# Always append /custom-agent-evaluations so users only need to provide /api/v1
|
|
54
|
+
_api_base = (
|
|
55
|
+
base_url or os.getenv("AGENTX_API_BASE_URL", _UTIL_API_BASE)
|
|
56
|
+
).rstrip("/")
|
|
57
|
+
if not _api_base.endswith("/custom-agent-evaluations"):
|
|
58
|
+
_api_base = f"{_api_base}/custom-agent-evaluations"
|
|
59
|
+
self._base_url = _api_base
|
|
60
|
+
self._session = requests.Session()
|
|
61
|
+
self._session.headers.update(
|
|
62
|
+
{
|
|
63
|
+
"x-api-key": self._api_key,
|
|
64
|
+
"Content-Type": "application/json",
|
|
65
|
+
"User-Agent": f"{SDK_NAME}/{self._sdk_version}",
|
|
66
|
+
"accept": "*/*",
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
# Expose dataset builder factory
|
|
70
|
+
from agentx.evaluations.datasets import DatasetClient
|
|
71
|
+
|
|
72
|
+
self.datasets = DatasetClient(self)
|
|
73
|
+
|
|
74
|
+
# ------------------------------------------------------------------
|
|
75
|
+
# Low-level HTTP
|
|
76
|
+
# ------------------------------------------------------------------
|
|
77
|
+
|
|
78
|
+
def _request(self, method: str, path: str, timeout: int = 30, **kwargs) -> Any:
|
|
79
|
+
url = f"{self._base_url}{path}"
|
|
80
|
+
last_exc: Optional[Exception] = None
|
|
81
|
+
for attempt, wait in enumerate([0.0] + _RETRY_BACKOFF):
|
|
82
|
+
if wait:
|
|
83
|
+
time.sleep(wait)
|
|
84
|
+
try:
|
|
85
|
+
resp = self._session.request(method, url, timeout=timeout, **kwargs)
|
|
86
|
+
except requests.RequestException as e:
|
|
87
|
+
last_exc = e
|
|
88
|
+
logger.debug("Request error (attempt %d): %s", attempt + 1, e)
|
|
89
|
+
continue
|
|
90
|
+
|
|
91
|
+
if resp.status_code == 401:
|
|
92
|
+
raise AgentXAuthError("Invalid or missing API key")
|
|
93
|
+
if resp.status_code == 422:
|
|
94
|
+
raise AgentXValidationError(resp.text)
|
|
95
|
+
if resp.status_code in _RETRYABLE_STATUS and attempt < _MAX_RETRIES - 1:
|
|
96
|
+
logger.debug(
|
|
97
|
+
"Retryable status %d (attempt %d)", resp.status_code, attempt + 1
|
|
98
|
+
)
|
|
99
|
+
last_exc = AgentXEvaluationsError(f"HTTP {resp.status_code}")
|
|
100
|
+
continue
|
|
101
|
+
if not resp.ok:
|
|
102
|
+
raise AgentXEvaluationsError(f"HTTP {resp.status_code}: {resp.text}")
|
|
103
|
+
try:
|
|
104
|
+
return resp.json()
|
|
105
|
+
except Exception:
|
|
106
|
+
return resp.text
|
|
107
|
+
raise AgentXEvaluationsError(f"Request failed after retries: {last_exc}")
|
|
108
|
+
|
|
109
|
+
# ------------------------------------------------------------------
|
|
110
|
+
# Dataset endpoints
|
|
111
|
+
# ------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
def create_dataset(self, payload: dict) -> Dataset:
|
|
114
|
+
data = self._request("POST", "/datasets", json=payload)
|
|
115
|
+
return Dataset(**data)
|
|
116
|
+
|
|
117
|
+
def list_datasets(self) -> List[Dataset]:
|
|
118
|
+
data = self._request("GET", "/datasets")
|
|
119
|
+
return [
|
|
120
|
+
Dataset(**d)
|
|
121
|
+
for d in (data if isinstance(data, list) else data.get("datasets", []))
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
def get_dataset(self, dataset_id: str) -> Dataset:
|
|
125
|
+
data = self._request("GET", f"/datasets/{dataset_id}")
|
|
126
|
+
return Dataset(**data)
|
|
127
|
+
|
|
128
|
+
# ------------------------------------------------------------------
|
|
129
|
+
# Run endpoints
|
|
130
|
+
# ------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
def init_run(
|
|
133
|
+
self,
|
|
134
|
+
dataset_id: str,
|
|
135
|
+
subject: EvaluationSubject,
|
|
136
|
+
python_version: Optional[str] = None,
|
|
137
|
+
) -> EvaluationRun:
|
|
138
|
+
from agentx.version import VERSION
|
|
139
|
+
|
|
140
|
+
payload = {
|
|
141
|
+
"datasetId": dataset_id,
|
|
142
|
+
"evaluationSubject": subject.model_dump(by_alias=True, exclude_none=True),
|
|
143
|
+
"runSource": "sdk",
|
|
144
|
+
"sdk": {
|
|
145
|
+
"name": SDK_NAME,
|
|
146
|
+
"version": VERSION,
|
|
147
|
+
"runnerVersion": "1",
|
|
148
|
+
"pythonVersion": python_version or _python_version(),
|
|
149
|
+
},
|
|
150
|
+
}
|
|
151
|
+
data = self._request("POST", "/runs", json=payload)
|
|
152
|
+
return EvaluationRun(**data)
|
|
153
|
+
|
|
154
|
+
def append_results(
|
|
155
|
+
self, run_id: str, batch_id: str, results: List[EvaluationResult]
|
|
156
|
+
) -> BatchAppendResponse:
|
|
157
|
+
payload = {
|
|
158
|
+
"batchId": batch_id,
|
|
159
|
+
"results": [_result_to_payload(r) for r in results],
|
|
160
|
+
}
|
|
161
|
+
data = self._request("POST", f"/runs/{run_id}/results", json=payload)
|
|
162
|
+
return BatchAppendResponse(**data)
|
|
163
|
+
|
|
164
|
+
def finalize_run(self, run_id: str) -> Dict[str, Any]:
|
|
165
|
+
return self._request(
|
|
166
|
+
"POST", f"/runs/{run_id}/finalize", json={"status": "completed"}
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
def analyze_run(self, run_id: str) -> Dict[str, Any]:
|
|
170
|
+
return self._request("POST", f"/runs/{run_id}/analyze", json={}, timeout=300)
|
|
171
|
+
|
|
172
|
+
def get_run(self, run_id: str) -> Dict[str, Any]:
|
|
173
|
+
return self._request("GET", f"/runs/{run_id}")
|
|
174
|
+
|
|
175
|
+
def get_report(self, run_id: str) -> Report:
|
|
176
|
+
data = self._request("GET", f"/runs/{run_id}/report")
|
|
177
|
+
return Report(**data)
|
|
178
|
+
|
|
179
|
+
def get_missing_results(self, run_id: str) -> List[Dict[str, Any]]:
|
|
180
|
+
data = self._request("GET", f"/runs/{run_id}/missing-results")
|
|
181
|
+
return data if isinstance(data, list) else data.get("missing", [])
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ---------------------------------------------------------------------------
|
|
185
|
+
# Helpers
|
|
186
|
+
# ---------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _result_to_payload(r: EvaluationResult) -> dict:
|
|
190
|
+
d = r.model_dump(by_alias=True, exclude_none=True)
|
|
191
|
+
# Rename snake_case fields the model may have stored locally
|
|
192
|
+
d["caseId"] = d.pop("case_id", d.get("caseId"))
|
|
193
|
+
d["questionIndex"] = d.pop("question_index", d.get("questionIndex"))
|
|
194
|
+
d["runNumber"] = d.pop("run_number", d.get("runNumber"))
|
|
195
|
+
d["idempotencyKey"] = d.pop("idempotency_key", d.get("idempotencyKey"))
|
|
196
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _python_version() -> str:
|
|
200
|
+
import sys
|
|
201
|
+
|
|
202
|
+
return f"{sys.version_info.major}.{sys.version_info.minor}"
|