agentaxiom 0.1.0__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.
agentaxiom/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """AgentAxiom: minimized, replayable, evidence-backed agent contracts."""
2
+
3
+ from .comparison import ComparisonPolicy, ComparisonResult, compare
4
+ from .contracts import Contract, ContractResult, evaluate_contract
5
+ from .models import Scenario, Transcript, Turn
6
+ from .pricing import ModelPricing, PricingCatalog
7
+ from .replay import ReplayPolicy, ReplayRunner
8
+
9
+ __all__ = [
10
+ "Contract",
11
+ "ContractResult",
12
+ "evaluate_contract",
13
+ "ComparisonPolicy",
14
+ "ComparisonResult",
15
+ "compare",
16
+ "ModelPricing",
17
+ "PricingCatalog",
18
+ "Scenario",
19
+ "Turn",
20
+ "Transcript",
21
+ "ReplayRunner",
22
+ "ReplayPolicy",
23
+ ]
24
+ __version__ = "0.1.0"
agentaxiom/cli.py ADDED
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from .comparison import ComparisonPolicy, compare
8
+ from .contracts import Contract, evaluate_contract
9
+ from .evidence import write_bundle
10
+ from .minimize import minimize_conversation
11
+ from .models import Transcript
12
+ from .service import main as serve
13
+
14
+
15
+ def main() -> int:
16
+ parser = argparse.ArgumentParser(prog="agentaxiom")
17
+ sub = parser.add_subparsers(dest="command", required=True)
18
+ check = sub.add_parser("check")
19
+ check.add_argument("transcript")
20
+ check.add_argument("contract")
21
+ check.add_argument("--evidence-dir", default="agentaxiom-evidence")
22
+ diff = sub.add_parser("compare")
23
+ diff.add_argument("baseline")
24
+ diff.add_argument("candidate")
25
+ diff.add_argument("--policy")
26
+ minimize = sub.add_parser("minimize")
27
+ minimize.add_argument("transcript")
28
+ minimize.add_argument("contract")
29
+ minimize.add_argument("--output", required=True)
30
+ sub.add_parser("serve", help="start the plain-language browser console")
31
+ args = parser.parse_args()
32
+ if args.command == "serve":
33
+ serve()
34
+ return 0
35
+ if args.command == "check":
36
+ transcript = Transcript.from_dict(json.loads(Path(args.transcript).read_text()))
37
+ contract = Contract(**json.loads(Path(args.contract).read_text()))
38
+ result = evaluate_contract(transcript, contract)
39
+ write_bundle(args.evidence_dir, transcript, result)
40
+ print(json.dumps({"passed": result.passed, "violations": result.violations}))
41
+ return 0 if result.passed else 1
42
+ if args.command == "compare":
43
+ baseline = Transcript.from_dict(json.loads(Path(args.baseline).read_text()))
44
+ candidate = Transcript.from_dict(json.loads(Path(args.candidate).read_text()))
45
+ policy = ComparisonPolicy(**json.loads(Path(args.policy).read_text())) if args.policy else ComparisonPolicy()
46
+ result = compare(baseline, candidate, policy)
47
+ print(json.dumps({"equivalent": result.equivalent, "regressions": result.regressions}))
48
+ return 0 if result.equivalent else 1
49
+ if args.command == "minimize":
50
+ recorded = Transcript.from_dict(json.loads(Path(args.transcript).read_text()))
51
+ contract = Contract(**json.loads(Path(args.contract).read_text()))
52
+ if evaluate_contract(recorded, contract).passed:
53
+ print(json.dumps({"error": "refusing to minimize a passing transcript"}))
54
+ return 2
55
+ minimized = minimize_conversation(recorded, lambda trace: not evaluate_contract(trace, contract).passed)
56
+ Path(args.output).write_text(json.dumps(minimized.to_dict(), indent=2, sort_keys=True), encoding="utf-8")
57
+ print(
58
+ json.dumps(
59
+ {
60
+ "turns_before": len(recorded.scenario.turns),
61
+ "turns_after": len(minimized.scenario.turns),
62
+ "output": args.output,
63
+ }
64
+ )
65
+ )
66
+ return 0
67
+ return 2
68
+
69
+
70
+ if __name__ == "__main__":
71
+ raise SystemExit(main())
@@ -0,0 +1,106 @@
1
+ """Deterministic cross-model/version regression comparison."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ from .models import Transcript, stable_hash
10
+
11
+
12
+ @dataclass
13
+ class ComparisonPolicy:
14
+ name: str = "default"
15
+ compare_structured_output: bool = True
16
+ compare_tool_sequence: bool = True
17
+ compare_safety: bool = True
18
+ compare_citation_domains: bool = False
19
+ max_latency_regression_ratio: float | None = 1.5
20
+ max_cost_regression_ratio: float | None = 1.5
21
+ ignored_output_paths: list[str] = field(default_factory=list)
22
+ normalize_whitespace: bool = True
23
+
24
+
25
+ @dataclass
26
+ class ComparisonResult:
27
+ policy: str
28
+ equivalent: bool
29
+ regressions: list[dict[str, Any]]
30
+ baseline_evidence_id: str
31
+ candidate_evidence_id: str
32
+
33
+
34
+ def _drop_paths(value: Any, ignored: list[str]) -> Any:
35
+ value = json.loads(json.dumps(value))
36
+ for path in ignored:
37
+ current = value
38
+ pieces = [part for part in path.strip("/").split("/") if part]
39
+ for piece in pieces[:-1]:
40
+ if isinstance(current, dict):
41
+ current = current.get(piece, {})
42
+ elif isinstance(current, list) and piece.isdigit() and int(piece) < len(current):
43
+ current = current[int(piece)]
44
+ else:
45
+ current = {}
46
+ if pieces and isinstance(current, dict):
47
+ current.pop(pieces[-1], None)
48
+ return value
49
+
50
+
51
+ def _tool_signature(calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
52
+ return [
53
+ {
54
+ "name": call.get("name") or call.get("function", {}).get("name"),
55
+ "arguments": call.get("arguments", call.get("function", {}).get("arguments", {})),
56
+ }
57
+ for call in calls
58
+ ]
59
+
60
+
61
+ def compare(baseline: Transcript, candidate: Transcript, policy: ComparisonPolicy | None = None) -> ComparisonResult:
62
+ policy = policy or ComparisonPolicy()
63
+ regressions: list[dict[str, Any]] = []
64
+ if baseline.scenario.prompt_hash != candidate.scenario.prompt_hash:
65
+ regressions.append(
66
+ {
67
+ "kind": "scenario_mismatch",
68
+ "baseline": baseline.scenario.prompt_hash,
69
+ "candidate": candidate.scenario.prompt_hash,
70
+ }
71
+ )
72
+ if policy.compare_structured_output:
73
+ before, after = (
74
+ _drop_paths(baseline.invocation.structured_output, policy.ignored_output_paths),
75
+ _drop_paths(candidate.invocation.structured_output, policy.ignored_output_paths),
76
+ )
77
+ if stable_hash(before) != stable_hash(after):
78
+ regressions.append({"kind": "structured_output", "baseline": before, "candidate": after})
79
+ if policy.compare_tool_sequence:
80
+ before, after = (
81
+ _tool_signature(baseline.invocation.tool_calls),
82
+ _tool_signature(candidate.invocation.tool_calls),
83
+ )
84
+ if before != after:
85
+ regressions.append({"kind": "tool_sequence", "baseline": before, "candidate": after})
86
+ if policy.compare_safety and baseline.invocation.safety != candidate.invocation.safety:
87
+ regressions.append(
88
+ {"kind": "safety", "baseline": baseline.invocation.safety, "candidate": candidate.invocation.safety}
89
+ )
90
+ if policy.compare_citation_domains:
91
+ from urllib.parse import urlparse
92
+
93
+ before = sorted(urlparse(c.get("uri", "")).netloc for c in baseline.invocation.citations)
94
+ after = sorted(urlparse(c.get("uri", "")).netloc for c in candidate.invocation.citations)
95
+ if before != after:
96
+ regressions.append({"kind": "citation_domains", "baseline": before, "candidate": after})
97
+ for metric, ratio in [
98
+ ("latency_ms", policy.max_latency_regression_ratio),
99
+ ("estimated_cost_usd", policy.max_cost_regression_ratio),
100
+ ]:
101
+ old, new = getattr(baseline.invocation, metric), getattr(candidate.invocation, metric)
102
+ if ratio is not None and old > 0 and new / old > ratio:
103
+ regressions.append(
104
+ {"kind": f"{metric}_regression", "baseline": old, "candidate": new, "maximum_ratio": ratio}
105
+ )
106
+ return ComparisonResult(policy.name, not regressions, regressions, baseline.evidence_id, candidate.evidence_id)
@@ -0,0 +1,127 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+ from jsonschema import Draft202012Validator
7
+
8
+ from .models import Transcript
9
+
10
+
11
+ class ContractValidationError(ValueError):
12
+ """Raised when a contract is self-contradictory or unsafe to evaluate."""
13
+
14
+
15
+ @dataclass
16
+ class Contract:
17
+ name: str
18
+ output_schema: dict[str, Any] | None = None
19
+ required_tools: list[str] = field(default_factory=list)
20
+ forbidden_tools: list[str] = field(default_factory=list)
21
+ tool_argument_schemas: dict[str, dict[str, Any]] = field(default_factory=dict)
22
+ tool_output_schemas: dict[str, dict[str, Any]] = field(default_factory=dict)
23
+ require_citations: bool = False
24
+ allowed_citation_domains: list[str] = field(default_factory=list)
25
+ minimum_citations: int = 0
26
+ allowed_safety_actions: list[str] | None = None
27
+ max_latency_ms: float | None = None
28
+ max_cost_usd: float | None = None
29
+
30
+
31
+ @dataclass
32
+ class ContractResult:
33
+ contract: str
34
+ passed: bool
35
+ violations: list[dict[str, Any]]
36
+
37
+
38
+ def evaluate_contract(transcript: Transcript, contract: Contract) -> ContractResult:
39
+ validate_contract(contract)
40
+ inv = transcript.invocation
41
+ violations: list[dict[str, Any]] = []
42
+ if contract.output_schema:
43
+ for error in Draft202012Validator(contract.output_schema).iter_errors(inv.structured_output):
44
+ violations.append({"kind": "schema", "path": list(error.path), "message": error.message})
45
+ called = {call.get("name") or call.get("function", {}).get("name") for call in inv.tool_calls}
46
+ for name in contract.required_tools:
47
+ if name not in called:
48
+ violations.append({"kind": "tool_missing", "tool": name})
49
+ for name in contract.forbidden_tools:
50
+ if name in called:
51
+ violations.append({"kind": "tool_forbidden", "tool": name})
52
+ for call in inv.tool_calls:
53
+ name = call.get("name") or call.get("function", {}).get("name")
54
+ schema = contract.tool_argument_schemas.get(name)
55
+ if schema:
56
+ arguments = call.get("arguments", call.get("function", {}).get("arguments", {}))
57
+ for error in Draft202012Validator(schema).iter_errors(arguments):
58
+ violations.append(
59
+ {"kind": "tool_arguments", "tool": name, "path": list(error.path), "message": error.message}
60
+ )
61
+ for turn in transcript.scenario.turns:
62
+ if turn.role == "tool" and turn.tool_name in contract.tool_output_schemas:
63
+ for error in Draft202012Validator(contract.tool_output_schemas[turn.tool_name]).iter_errors(
64
+ turn.tool_output
65
+ ):
66
+ violations.append(
67
+ {"kind": "tool_output", "tool": turn.tool_name, "path": list(error.path), "message": error.message}
68
+ )
69
+ if contract.require_citations and not inv.citations:
70
+ violations.append({"kind": "grounding", "message": "response has no citations"})
71
+ if len(inv.citations) < contract.minimum_citations:
72
+ violations.append(
73
+ {"kind": "citation_count", "actual": len(inv.citations), "minimum": contract.minimum_citations}
74
+ )
75
+ if contract.allowed_citation_domains:
76
+ from urllib.parse import urlparse
77
+
78
+ allowed = set(contract.allowed_citation_domains)
79
+ for citation in inv.citations:
80
+ uri = citation.get("uri") or citation.get("web", {}).get("uri") or ""
81
+ if not uri or urlparse(uri).netloc not in allowed:
82
+ violations.append({"kind": "citation_domain", "uri": uri, "allowed": sorted(allowed)})
83
+ action = inv.safety.get("action")
84
+ if contract.allowed_safety_actions is not None and action not in contract.allowed_safety_actions:
85
+ violations.append({"kind": "safety", "actual": action, "allowed": contract.allowed_safety_actions})
86
+ if contract.max_latency_ms is not None and inv.latency_ms > contract.max_latency_ms:
87
+ violations.append({"kind": "latency_budget", "actual": inv.latency_ms, "maximum": contract.max_latency_ms})
88
+ if contract.max_cost_usd is not None and inv.estimated_cost_usd > contract.max_cost_usd:
89
+ violations.append({"kind": "cost_budget", "actual": inv.estimated_cost_usd, "maximum": contract.max_cost_usd})
90
+ return ContractResult(contract=contract.name, passed=not violations, violations=violations)
91
+
92
+
93
+ def validate_contract(contract: Contract) -> None:
94
+ if not isinstance(contract.name, str) or not contract.name.strip():
95
+ raise ContractValidationError("contract.name must be a non-empty string")
96
+ overlap = set(contract.required_tools) & set(contract.forbidden_tools)
97
+ if overlap:
98
+ raise ContractValidationError(f"tools cannot be both required and forbidden: {sorted(overlap)}")
99
+ for attribute in ("required_tools", "forbidden_tools", "allowed_citation_domains"):
100
+ values = getattr(contract, attribute)
101
+ if not isinstance(values, list) or not all(isinstance(value, str) and value.strip() for value in values):
102
+ raise ContractValidationError(f"contract.{attribute} must be a list of non-empty strings")
103
+ if contract.allowed_safety_actions is not None and (
104
+ not isinstance(contract.allowed_safety_actions, list)
105
+ or not all(isinstance(action, str) and action.strip() for action in contract.allowed_safety_actions)
106
+ ):
107
+ raise ContractValidationError("contract.allowed_safety_actions must be a list of non-empty strings or null")
108
+ for attribute in ("tool_argument_schemas", "tool_output_schemas"):
109
+ values = getattr(contract, attribute)
110
+ if not isinstance(values, dict) or not all(
111
+ isinstance(name, str) and isinstance(schema, dict) for name, schema in values.items()
112
+ ):
113
+ raise ContractValidationError(f"contract.{attribute} must map tool names to JSON Schema objects")
114
+ for limit in (contract.max_latency_ms, contract.max_cost_usd):
115
+ if limit is not None and (not isinstance(limit, (int, float)) or limit < 0):
116
+ raise ContractValidationError("contract budgets must be non-negative numbers")
117
+ if not isinstance(contract.minimum_citations, int) or contract.minimum_citations < 0:
118
+ raise ContractValidationError("contract.minimum_citations must be a non-negative integer")
119
+ schemas = [contract.output_schema, *contract.tool_argument_schemas.values(), *contract.tool_output_schemas.values()]
120
+ for schema in schemas:
121
+ if schema is not None:
122
+ if not isinstance(schema, dict):
123
+ raise ContractValidationError("contract schemas must be JSON objects")
124
+ try:
125
+ Draft202012Validator.check_schema(schema)
126
+ except Exception as exc:
127
+ raise ContractValidationError(f"contract includes an invalid JSON Schema: {exc}") from exc
agentaxiom/evidence.py ADDED
@@ -0,0 +1,83 @@
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ import json
5
+ import re
6
+ import tempfile
7
+ from dataclasses import asdict
8
+ from hashlib import sha256
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .contracts import ContractResult
13
+ from .models import Transcript
14
+
15
+ DEFAULT_SECRET_PATTERNS = [r"(?i)(api[_-]?key|authorization|token|password)\s*[:=]\s*[^\s,]+", r"AIza[\w-]{20,}"]
16
+ DEFAULT_PII_PATTERNS = [r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b", r"\b\d{3}-?\d{2}-?\d{4}\b"]
17
+ DEFAULT_REDACTION_PATTERNS = DEFAULT_SECRET_PATTERNS + DEFAULT_PII_PATTERNS
18
+
19
+
20
+ def redact(value: Any, patterns: list[str] = DEFAULT_REDACTION_PATTERNS) -> Any:
21
+ """Redact values recursively without breaking otherwise-valid JSON evidence."""
22
+ if isinstance(value, dict):
23
+ return {
24
+ key: (
25
+ "[REDACTED]"
26
+ if re.search(r"(?i)(api[_-]?key|authorization|token|password|secret|email|phone|ssn)", key)
27
+ else redact(item, patterns)
28
+ )
29
+ for key, item in value.items()
30
+ }
31
+ if isinstance(value, list):
32
+ return [redact(item, patterns) for item in value]
33
+ if isinstance(value, str):
34
+ for pattern in patterns:
35
+ value = re.sub(pattern, "[REDACTED]", value)
36
+ return value
37
+
38
+
39
+ def write_bundle(
40
+ directory: str | Path, transcript: Transcript, result: ContractResult, extra: dict[str, Any] | None = None
41
+ ) -> Path:
42
+ target = Path(directory)
43
+ target.mkdir(parents=True, exist_ok=True)
44
+ payload = redact({"transcript": transcript.to_dict(), "result": asdict(result), "extra": extra or {}})
45
+ encoded = json.dumps(payload, indent=2, sort_keys=True)
46
+ _atomic_write(target / "evidence.json", encoded)
47
+ _atomic_write(
48
+ target / "manifest.json",
49
+ json.dumps(
50
+ {
51
+ "schema_version": transcript.schema_version,
52
+ "evidence_id": transcript.evidence_id,
53
+ "files": {"evidence.json": sha256(encoded.encode()).hexdigest()},
54
+ },
55
+ indent=2,
56
+ ),
57
+ )
58
+ status = "PASS" if result.passed else "FAIL"
59
+ body = html.escape(json.dumps(payload, indent=2, sort_keys=True))
60
+ page = (
61
+ f"<!doctype html><meta charset=utf-8><title>AgentAxiom {status}</title>"
62
+ f"<h1>{status}: {html.escape(result.contract)}</h1><pre>{body}</pre>"
63
+ )
64
+ _atomic_write(
65
+ target / "index.html",
66
+ page,
67
+ )
68
+ return target
69
+
70
+
71
+ def verify_bundle(directory: str | Path) -> bool:
72
+ target = Path(directory)
73
+ manifest = json.loads((target / "manifest.json").read_text(encoding="utf-8"))
74
+ evidence = (target / "evidence.json").read_bytes()
75
+ return sha256(evidence).hexdigest() == manifest["files"]["evidence.json"]
76
+
77
+
78
+ def _atomic_write(path: Path, content: str) -> None:
79
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="\n", dir=path.parent, delete=False) as handle:
80
+ handle.write(content)
81
+ handle.flush()
82
+ temp_path = Path(handle.name)
83
+ temp_path.replace(path)
agentaxiom/exports.py ADDED
@@ -0,0 +1,45 @@
1
+ """Optional GCS and BigQuery evidence sinks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import asdict
7
+ from typing import Any
8
+
9
+ from .contracts import ContractResult
10
+ from .evidence import redact
11
+ from .models import Transcript
12
+
13
+
14
+ def export_gcs(bucket: str, prefix: str, transcript: Transcript, result: ContractResult) -> str:
15
+ try:
16
+ from google.cloud import storage
17
+ except ImportError as exc:
18
+ raise ImportError("Install AgentAxiom's export extra: pip install -e '.[export]'") from exc
19
+ name = f"{prefix.strip('/')}/{transcript.scenario.name}/evidence.json"
20
+ payload = redact({"transcript": transcript.to_dict(), "result": asdict(result)})
21
+ storage.Client().bucket(bucket).blob(name).upload_from_string(
22
+ json.dumps(payload, default=str), content_type="application/json"
23
+ )
24
+ return f"gs://{bucket}/{name}"
25
+
26
+
27
+ def export_bigquery(table: str, transcript: Transcript, result: ContractResult) -> None:
28
+ try:
29
+ from google.cloud import bigquery
30
+ except ImportError as exc:
31
+ raise ImportError("Install AgentAxiom's export extra: pip install -e '.[export]'") from exc
32
+ row: dict[str, Any] = {
33
+ "scenario": transcript.scenario.name,
34
+ "prompt_hash": transcript.scenario.prompt_hash,
35
+ "model": transcript.invocation.model,
36
+ "region": transcript.invocation.region,
37
+ "passed": result.passed,
38
+ "violations": json.dumps(result.violations),
39
+ "latency_ms": transcript.invocation.latency_ms,
40
+ "cost_usd": transcript.invocation.estimated_cost_usd,
41
+ "recorded_at": transcript.invocation.timestamp,
42
+ }
43
+ errors = bigquery.Client().insert_rows_json(table, [row])
44
+ if errors:
45
+ raise RuntimeError(f"BigQuery export failed: {errors}")
agentaxiom/minimize.py ADDED
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+
5
+ from .models import Invocation, Scenario, Transcript
6
+
7
+
8
+ def minimize_conversation(recorded: Transcript, still_fails: Callable[[Transcript], bool]) -> Transcript:
9
+ """Delta-debug user-visible turns while retaining a reproducible failing trace."""
10
+ turns = recorded.scenario.turns[:]
11
+ granularity = 2
12
+ while len(turns) > 1:
13
+ chunk = max(1, len(turns) // granularity)
14
+ reduced = False
15
+ for start in range(0, len(turns), chunk):
16
+ candidate = turns[:start] + turns[start + chunk :]
17
+ if candidate and still_fails(
18
+ Transcript(Scenario(recorded.scenario.name, candidate, recorded.scenario.metadata), recorded.invocation)
19
+ ):
20
+ turns, granularity, reduced = candidate, max(2, granularity - 1), True
21
+ break
22
+ if not reduced:
23
+ if granularity >= len(turns):
24
+ break
25
+ granularity = min(len(turns), granularity * 2)
26
+ return Transcript(Scenario(recorded.scenario.name, turns, recorded.scenario.metadata), recorded.invocation)
27
+
28
+
29
+ def minimize_with_replay(
30
+ recorded: Transcript, replay: Callable[[Scenario], Invocation], still_fails: Callable[[Transcript], bool]
31
+ ) -> Transcript:
32
+ """Minimize only when each candidate is freshly replayed by the caller."""
33
+
34
+ def verified_failure(candidate: Transcript) -> bool:
35
+ fresh = Transcript(candidate.scenario, replay(candidate.scenario), candidate.schema_version)
36
+ return still_fails(fresh)
37
+
38
+ return minimize_conversation(recorded, verified_failure)
agentaxiom/models.py ADDED
@@ -0,0 +1,130 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import asdict, dataclass, field
4
+ from datetime import datetime, timezone
5
+ from hashlib import sha256
6
+ from typing import Any, Literal
7
+
8
+
9
+ class TranscriptValidationError(ValueError):
10
+ """Raised when untrusted transcript data is not safe to evaluate."""
11
+
12
+
13
+ MAX_TURNS = 100
14
+ MAX_TEXT_CHARS = 200_000
15
+ MAX_TOOL_CALLS = 100
16
+
17
+
18
+ def stable_hash(value: Any) -> str:
19
+ import json
20
+
21
+ return sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), default=str).encode()).hexdigest()
22
+
23
+
24
+ @dataclass
25
+ class Turn:
26
+ role: Literal["system", "user", "assistant", "tool"]
27
+ content: str | None = None
28
+ tool_name: str | None = None
29
+ tool_input: dict[str, Any] | None = None
30
+ tool_output: Any = None
31
+
32
+
33
+ @dataclass
34
+ class Scenario:
35
+ name: str
36
+ turns: list[Turn]
37
+ metadata: dict[str, Any] = field(default_factory=dict)
38
+
39
+ @property
40
+ def prompt_hash(self) -> str:
41
+ return stable_hash([asdict(turn) for turn in self.turns])
42
+
43
+
44
+ @dataclass
45
+ class Invocation:
46
+ model: str
47
+ region: str
48
+ provider: str = "offline"
49
+ generation: dict[str, Any] = field(default_factory=dict)
50
+ tools: list[dict[str, Any]] = field(default_factory=list)
51
+ adk_version: str | None = None
52
+ response_text: str | None = None
53
+ structured_output: Any = None
54
+ tool_calls: list[dict[str, Any]] = field(default_factory=list)
55
+ citations: list[dict[str, Any]] = field(default_factory=list)
56
+ safety: dict[str, Any] = field(default_factory=dict)
57
+ token_usage: dict[str, int] = field(default_factory=dict)
58
+ latency_ms: float = 0.0
59
+ estimated_cost_usd: float = 0.0
60
+ raw_response: dict[str, Any] = field(default_factory=dict)
61
+ request_id: str | None = None
62
+ trace_id: str | None = None
63
+ labels: dict[str, str] = field(default_factory=dict)
64
+ timestamp: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
65
+
66
+
67
+ @dataclass
68
+ class Transcript:
69
+ scenario: Scenario
70
+ invocation: Invocation
71
+ schema_version: str = "v1"
72
+
73
+ def to_dict(self) -> dict[str, Any]:
74
+ return asdict(self)
75
+
76
+ @property
77
+ def evidence_id(self) -> str:
78
+ """Stable identity for grouping equivalent captured evidence."""
79
+ return stable_hash(
80
+ {
81
+ "prompt": self.scenario.prompt_hash,
82
+ "invocation": self.invocation.model,
83
+ "generation": self.invocation.generation,
84
+ }
85
+ )
86
+
87
+ @classmethod
88
+ def from_dict(cls, data: dict[str, Any]) -> Transcript:
89
+ validate_transcript_data(data)
90
+ scenario = Scenario(
91
+ turns=[Turn(**turn) for turn in data["scenario"]["turns"]],
92
+ name=data["scenario"]["name"],
93
+ metadata=data["scenario"].get("metadata", {}),
94
+ )
95
+ return cls(
96
+ scenario=scenario,
97
+ invocation=Invocation(**data["invocation"]),
98
+ schema_version=data.get("schema_version", "v1"),
99
+ )
100
+
101
+
102
+ def validate_transcript_data(data: Any) -> None:
103
+ """Bound and validate untrusted JSON before it becomes a transcript object."""
104
+ if not isinstance(data, dict):
105
+ raise TranscriptValidationError("transcript must be a JSON object")
106
+ scenario, invocation = data.get("scenario"), data.get("invocation")
107
+ if not isinstance(scenario, dict) or not isinstance(invocation, dict):
108
+ raise TranscriptValidationError("transcript requires scenario and invocation objects")
109
+ if not isinstance(scenario.get("name"), str) or not scenario["name"].strip():
110
+ raise TranscriptValidationError("scenario.name must be a non-empty string")
111
+ turns = scenario.get("turns")
112
+ if not isinstance(turns, list) or not turns or len(turns) > MAX_TURNS:
113
+ raise TranscriptValidationError(f"scenario.turns must contain 1 to {MAX_TURNS} turns")
114
+ for index, turn in enumerate(turns):
115
+ if not isinstance(turn, dict) or turn.get("role") not in {"system", "user", "assistant", "tool"}:
116
+ raise TranscriptValidationError(f"turn {index} has an invalid role")
117
+ if turn.get("content") is not None and (
118
+ not isinstance(turn["content"], str) or len(turn["content"]) > MAX_TEXT_CHARS
119
+ ):
120
+ raise TranscriptValidationError(f"turn {index} content must be text under {MAX_TEXT_CHARS} characters")
121
+ for attribute in ("model", "region"):
122
+ if not isinstance(invocation.get(attribute), str) or not invocation[attribute].strip():
123
+ raise TranscriptValidationError(f"invocation.{attribute} must be a non-empty string")
124
+ tool_calls = invocation.get("tool_calls", [])
125
+ if not isinstance(tool_calls, list) or len(tool_calls) > MAX_TOOL_CALLS:
126
+ raise TranscriptValidationError(f"invocation.tool_calls must contain at most {MAX_TOOL_CALLS} calls")
127
+ for attribute in ("latency_ms", "estimated_cost_usd"):
128
+ value = invocation.get(attribute, 0)
129
+ if not isinstance(value, (int, float)) or value < 0:
130
+ raise TranscriptValidationError(f"invocation.{attribute} must be a non-negative number")
agentaxiom/pricing.py ADDED
@@ -0,0 +1,28 @@
1
+ """Explicit, versioned cost estimation; no hidden or remotely fetched pricing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class ModelPricing:
10
+ input_per_million_usd: float
11
+ output_per_million_usd: float
12
+
13
+
14
+ @dataclass
15
+ class PricingCatalog:
16
+ rates: dict[str, ModelPricing] = field(default_factory=dict)
17
+ version: str = "user-supplied"
18
+
19
+ def estimate(self, model: str, usage: dict[str, int]) -> float:
20
+ """Returns zero for unknown models: caller must never treat it as a quote."""
21
+ rate = self.rates.get(model)
22
+ if not rate:
23
+ return 0.0
24
+ return round(
25
+ (usage.get("input", 0) * rate.input_per_million_usd + usage.get("output", 0) * rate.output_per_million_usd)
26
+ / 1_000_000,
27
+ 8,
28
+ )