spooling 0.3.0__tar.gz → 0.4.0__tar.gz

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.
Files changed (85) hide show
  1. {spooling-0.3.0/spooling.egg-info → spooling-0.4.0}/PKG-INFO +10 -6
  2. {spooling-0.3.0 → spooling-0.4.0}/README.md +3 -3
  3. {spooling-0.3.0 → spooling-0.4.0}/pyproject.toml +9 -3
  4. {spooling-0.3.0 → spooling-0.4.0}/spooling/__init__.py +1 -1
  5. {spooling-0.3.0 → spooling-0.4.0}/spooling/cli.py +2 -2
  6. {spooling-0.3.0 → spooling-0.4.0}/spooling/db.py +7 -0
  7. spooling-0.4.0/spooling/evals.py +537 -0
  8. spooling-0.4.0/spooling/experiments.py +307 -0
  9. {spooling-0.3.0 → spooling-0.4.0}/spooling/mcp_server.py +2 -2
  10. {spooling-0.3.0 → spooling-0.4.0}/spooling/remote_otel.py +25 -16
  11. {spooling-0.3.0 → spooling-0.4.0}/spooling/schema.py +7 -0
  12. {spooling-0.3.0 → spooling-0.4.0}/spooling/server.py +2 -2
  13. {spooling-0.3.0 → spooling-0.4.0}/spooling/summarize.py +1 -1
  14. {spooling-0.3.0 → spooling-0.4.0/spooling.egg-info}/PKG-INFO +10 -6
  15. {spooling-0.3.0 → spooling-0.4.0}/spooling.egg-info/SOURCES.txt +1 -0
  16. {spooling-0.3.0 → spooling-0.4.0}/spooling.egg-info/requires.txt +8 -2
  17. spooling-0.4.0/tests/test_evals.py +145 -0
  18. spooling-0.3.0/spooling/evals.py +0 -611
  19. spooling-0.3.0/spooling/experiments.py +0 -407
  20. {spooling-0.3.0 → spooling-0.4.0}/LICENSE +0 -0
  21. {spooling-0.3.0 → spooling-0.4.0}/setup.cfg +0 -0
  22. {spooling-0.3.0 → spooling-0.4.0}/spooling/agent.py +0 -0
  23. {spooling-0.3.0 → spooling-0.4.0}/spooling/classifiers.py +0 -0
  24. {spooling-0.3.0 → spooling-0.4.0}/spooling/cloud.py +0 -0
  25. {spooling-0.3.0 → spooling-0.4.0}/spooling/config.py +0 -0
  26. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/__init__.py +0 -0
  27. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/base.py +0 -0
  28. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/bigquery.py +0 -0
  29. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/clickhouse.py +0 -0
  30. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/factory.py +0 -0
  31. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/mongodb.py +0 -0
  32. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/mysql.py +0 -0
  33. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/postgresql.py +0 -0
  34. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/rest/__init__.py +0 -0
  35. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/rest/base.py +0 -0
  36. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/rest/shopify_connectors.py +0 -0
  37. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/snowflake.py +0 -0
  38. {spooling-0.3.0 → spooling-0.4.0}/spooling/connectors/types.py +0 -0
  39. {spooling-0.3.0 → spooling-0.4.0}/spooling/device_login.py +0 -0
  40. {spooling-0.3.0 → spooling-0.4.0}/spooling/embeddings.py +0 -0
  41. {spooling-0.3.0 → spooling-0.4.0}/spooling/ingest.py +0 -0
  42. {spooling-0.3.0 → spooling-0.4.0}/spooling/insights.py +0 -0
  43. {spooling-0.3.0 → spooling-0.4.0}/spooling/optimize.py +0 -0
  44. {spooling-0.3.0 → spooling-0.4.0}/spooling/parser.py +0 -0
  45. {spooling-0.3.0 → spooling-0.4.0}/spooling/pricing.py +0 -0
  46. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/__init__.py +0 -0
  47. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/antigravity.py +0 -0
  48. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/base.py +0 -0
  49. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/claude_code.py +0 -0
  50. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/codex.py +0 -0
  51. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/copilot.py +0 -0
  52. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/cortex_code.py +0 -0
  53. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/cursor.py +0 -0
  54. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/gemini.py +0 -0
  55. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/github.py +0 -0
  56. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/gitlab.py +0 -0
  57. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/kiro.py +0 -0
  58. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/opencode.py +0 -0
  59. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/session_file.py +0 -0
  60. {spooling-0.3.0 → spooling-0.4.0}/spooling/providers/windsurf.py +0 -0
  61. {spooling-0.3.0 → spooling-0.4.0}/spooling/redact.py +0 -0
  62. {spooling-0.3.0 → spooling-0.4.0}/spooling/sdk.py +0 -0
  63. {spooling-0.3.0 → spooling-0.4.0}/spooling/search.py +0 -0
  64. {spooling-0.3.0 → spooling-0.4.0}/spooling/sessions.py +0 -0
  65. {spooling-0.3.0 → spooling-0.4.0}/spooling/stats.py +0 -0
  66. {spooling-0.3.0 → spooling-0.4.0}/spooling/subscription_pricing.py +0 -0
  67. {spooling-0.3.0 → spooling-0.4.0}/spooling/tracing.py +0 -0
  68. {spooling-0.3.0 → spooling-0.4.0}/spooling/tunnel.py +0 -0
  69. {spooling-0.3.0 → spooling-0.4.0}/spooling/tunnel_auth.py +0 -0
  70. {spooling-0.3.0 → spooling-0.4.0}/spooling/watcher.py +0 -0
  71. {spooling-0.3.0 → spooling-0.4.0}/spooling.egg-info/dependency_links.txt +0 -0
  72. {spooling-0.3.0 → spooling-0.4.0}/spooling.egg-info/entry_points.txt +0 -0
  73. {spooling-0.3.0 → spooling-0.4.0}/spooling.egg-info/top_level.txt +0 -0
  74. {spooling-0.3.0 → spooling-0.4.0}/tests/test_agent_spans.py +0 -0
  75. {spooling-0.3.0 → spooling-0.4.0}/tests/test_claude_code_provider.py +0 -0
  76. {spooling-0.3.0 → spooling-0.4.0}/tests/test_cloud_errors.py +0 -0
  77. {spooling-0.3.0 → spooling-0.4.0}/tests/test_cloud_teams.py +0 -0
  78. {spooling-0.3.0 → spooling-0.4.0}/tests/test_device_login.py +0 -0
  79. {spooling-0.3.0 → spooling-0.4.0}/tests/test_docs.py +0 -0
  80. {spooling-0.3.0 → spooling-0.4.0}/tests/test_insights.py +0 -0
  81. {spooling-0.3.0 → spooling-0.4.0}/tests/test_mcp_auth_middleware.py +0 -0
  82. {spooling-0.3.0 → spooling-0.4.0}/tests/test_session_ids.py +0 -0
  83. {spooling-0.3.0 → spooling-0.4.0}/tests/test_storage_optimizations.py +0 -0
  84. {spooling-0.3.0 → spooling-0.4.0}/tests/test_summarize.py +0 -0
  85. {spooling-0.3.0 → spooling-0.4.0}/tests/test_tunnel_auth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spooling
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Local session tracker and semantic search for AI coding assistants
5
5
  Author: Parsed Analytics, Inc.
6
6
  License: MIT
@@ -19,8 +19,8 @@ Requires-Dist: watchdog>=4.0
19
19
  Requires-Dist: rich>=13.0
20
20
  Requires-Dist: httpx>=0.27
21
21
  Requires-Dist: anthropic>=0.40
22
- Requires-Dist: strands-agents[ollama]>=1.35
23
- Requires-Dist: strands-agents-evals>=0.1
22
+ Requires-Dist: pydantic-ai-slim[anthropic,openai]>=2.78
23
+ Requires-Dist: pydantic-evals>=2.78
24
24
  Requires-Dist: mcp<2,>=1.27
25
25
  Provides-Extra: dev
26
26
  Requires-Dist: pytest>=8.0; extra == "dev"
@@ -31,6 +31,10 @@ Requires-Dist: google-cloud-bigquery>=3.0; extra == "connectors"
31
31
  Requires-Dist: mysql-connector-python>=8.0; extra == "connectors"
32
32
  Requires-Dist: clickhouse-connect>=0.5; extra == "connectors"
33
33
  Requires-Dist: motor>=3.0; extra == "connectors"
34
+ Provides-Extra: otel-mappers
35
+ Requires-Dist: strands-agents-evals>=0.1; extra == "otel-mappers"
36
+ Provides-Extra: bedrock
37
+ Requires-Dist: boto3>=1.34; extra == "bedrock"
34
38
  Dynamic: license-file
35
39
 
36
40
  # Spooling
@@ -409,7 +413,7 @@ spooling eval run --rubric <id> --days 7 # Batch-score traces from the la
409
413
 
410
414
  ### `spooling experiment`
411
415
 
412
- Create and run Strands-style experiments — a set of test cases evaluated by one or more rubrics.
416
+ Create and run experiments — a set of test cases evaluated by one or more LLM judges (Pydantic Evals).
413
417
 
414
418
  ```bash
415
419
  spooling experiment list # List all experiments
@@ -420,7 +424,7 @@ spooling experiment show --run <run-id> # Show the results of a past run
420
424
 
421
425
  ### `spooling otel`
422
426
 
423
- Ingest OpenTelemetry / Strands span exports from external sources into Spooling.
427
+ Ingest OpenTelemetry span exports from external sources into Spooling. OTLP/JSON import needs the optional mapper extra: `pip install "spooling[otel-mappers]"`.
424
428
 
425
429
  ```bash
426
430
  spooling otel ingest --file spans.json # Ingest an OTLP JSON export
@@ -646,7 +650,7 @@ Or register it with an MCP client's config file.
646
650
  | `get_stats` | Top-line stats: traces, tokens, cost, errors |
647
651
  | `get_top_vendors` | Most-used external vendors by tool-call count |
648
652
  | `list_evals` | Recent eval runs, optionally filtered by rubric |
649
- | `list_rubrics` | All configured Strands eval rubrics |
653
+ | `list_rubrics` | All configured eval rubrics (LLM judges + function rubrics) |
650
654
  | `run_eval` | Run a rubric against a trace and persist the result |
651
655
 
652
656
  ### Stdio (legacy clients)
@@ -374,7 +374,7 @@ spooling eval run --rubric <id> --days 7 # Batch-score traces from the la
374
374
 
375
375
  ### `spooling experiment`
376
376
 
377
- Create and run Strands-style experiments — a set of test cases evaluated by one or more rubrics.
377
+ Create and run experiments — a set of test cases evaluated by one or more LLM judges (Pydantic Evals).
378
378
 
379
379
  ```bash
380
380
  spooling experiment list # List all experiments
@@ -385,7 +385,7 @@ spooling experiment show --run <run-id> # Show the results of a past run
385
385
 
386
386
  ### `spooling otel`
387
387
 
388
- Ingest OpenTelemetry / Strands span exports from external sources into Spooling.
388
+ Ingest OpenTelemetry span exports from external sources into Spooling. OTLP/JSON import needs the optional mapper extra: `pip install "spooling[otel-mappers]"`.
389
389
 
390
390
  ```bash
391
391
  spooling otel ingest --file spans.json # Ingest an OTLP JSON export
@@ -611,7 +611,7 @@ Or register it with an MCP client's config file.
611
611
  | `get_stats` | Top-line stats: traces, tokens, cost, errors |
612
612
  | `get_top_vendors` | Most-used external vendors by tool-call count |
613
613
  | `list_evals` | Recent eval runs, optionally filtered by rubric |
614
- | `list_rubrics` | All configured Strands eval rubrics |
614
+ | `list_rubrics` | All configured eval rubrics (LLM judges + function rubrics) |
615
615
  | `run_eval` | Run a rubric against a trace and persist the result |
616
616
 
617
617
  ### Stdio (legacy clients)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "spooling"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "Local session tracker and semantic search for AI coding assistants"
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Parsed Analytics, Inc." }]
@@ -21,8 +21,8 @@ dependencies = [
21
21
  "rich>=13.0",
22
22
  "httpx>=0.27",
23
23
  "anthropic>=0.40",
24
- "strands-agents[ollama]>=1.35",
25
- "strands-agents-evals>=0.1",
24
+ "pydantic-ai-slim[openai,anthropic]>=2.78",
25
+ "pydantic-evals>=2.78",
26
26
  "mcp>=1.27,<2",
27
27
  ]
28
28
 
@@ -38,6 +38,12 @@ connectors = [
38
38
  "clickhouse-connect>=0.5",
39
39
  "motor>=3.0",
40
40
  ]
41
+ otel-mappers = [
42
+ "strands-agents-evals>=0.1",
43
+ ]
44
+ bedrock = [
45
+ "boto3>=1.34",
46
+ ]
41
47
 
42
48
  [project.scripts]
43
49
  spooling = "spooling.cli:cli"
@@ -1,2 +1,2 @@
1
1
  """Spooling - local session tracker for AI coding assistants."""
2
- __version__ = "0.1.0"
2
+ __version__ = "0.4.0"
@@ -341,7 +341,7 @@ def serve(host, port):
341
341
 
342
342
  @cli.group()
343
343
  def otel():
344
- """Ingest OTel/Strands spans from external sources into Spooling."""
344
+ """Ingest OTel spans from external sources into Spooling."""
345
345
  pass
346
346
 
347
347
 
@@ -395,7 +395,7 @@ def otel_preview(path, provider_id, project):
395
395
 
396
396
  @cli.group()
397
397
  def experiment():
398
- """Create and run Strands experiments (cases + evaluators)."""
398
+ """Create and run experiments (cases + judges)."""
399
399
  pass
400
400
 
401
401
 
@@ -147,6 +147,13 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
147
147
  _ADDED_COLUMNS = (
148
148
  ("sessions", "summary", "TEXT"),
149
149
  ("sessions", "summary_message_count", "INTEGER"),
150
+ ("eval_rubrics", "evaluator_type", "TEXT"),
151
+ ("eval_rubrics", "rubric_text", "TEXT"),
152
+ ("eval_rubrics", "model_id", "TEXT"),
153
+ ("eval_rubrics", "is_default", "INTEGER DEFAULT 0"),
154
+ ("evals", "judge_cost_usd", "REAL DEFAULT 0"),
155
+ ("evals", "attrs", "TEXT DEFAULT '{}'"),
156
+ ("experiments", "config", "TEXT DEFAULT '{}'"),
150
157
  )
151
158
 
152
159
 
@@ -0,0 +1,537 @@
1
+ """Spooling eval runner backed by Pydantic Evals.
2
+
3
+ The rubric catalog lives in the `eval_rubrics` table. Each row either names a
4
+ judge (`evaluator_type` column) or is a function rubric handled by our own
5
+ registry below. When a rubric is run we:
6
+
7
+ 1. Load the rubric row + the target trace (or span) + its descendants.
8
+ 2. Build the judge inputs from the trace: the first user message as `input`
9
+ and the assistant's final output as `output` (plus a compact tool-call
10
+ transcript for trajectory-aware rubrics).
11
+ 3. Instantiate a Pydantic Evals `LLMJudge` with an Ollama model (qwen by
12
+ default) so it works out of the box with no API key required. Anthropic is
13
+ used instead when the judge is explicitly configured for it.
14
+ 4. Run the judge and persist the result into our `evals` table
15
+ (score / passed / reason / label).
16
+
17
+ Function rubrics (deterministic, non-LLM) still live in `_FUNCTION_RUBRICS`.
18
+ They short-circuit the judge path.
19
+
20
+ Custom rubrics are just rows with `evaluator_type='LLMJudge'` (or the legacy
21
+ `'OutputEvaluator'`) and a `rubric_text` value — anyone can add one via
22
+ POST /api/evals/rubrics. Legacy Strands evaluator_type names stored in older
23
+ databases are mapped to Pydantic Evals rubrics at read time, so no destructive
24
+ migration is required.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ import os
31
+ import uuid
32
+ from dataclasses import dataclass
33
+ from datetime import datetime, timezone
34
+ from typing import Any, Callable, Optional
35
+
36
+ from spooling.db import get_connection
37
+
38
+
39
+ # --- function rubric registry (deterministic) ------------------------------
40
+
41
+ FunctionGrader = Callable[[dict, list[dict]], "EvalResult"]
42
+ _FUNCTION_RUBRICS: dict[str, FunctionGrader] = {}
43
+
44
+
45
+ @dataclass
46
+ class EvalResult:
47
+ score: float | None = None
48
+ passed: bool | None = None
49
+ label: str | None = None
50
+ rationale: str | None = None
51
+ attrs: dict[str, Any] | None = None
52
+
53
+
54
+ def register_function_rubric(rubric_id: str):
55
+ def _wrap(fn: FunctionGrader) -> FunctionGrader:
56
+ _FUNCTION_RUBRICS[rubric_id] = fn
57
+ return fn
58
+ return _wrap
59
+
60
+
61
+ PASS_SCORE_THRESHOLD = 0.95
62
+
63
+
64
+ @register_function_rubric("tool-error-rate")
65
+ def _tool_error_rate(target: dict, children: list[dict]) -> EvalResult:
66
+ tool_spans = [c for c in children if c["kind"] == "tool"]
67
+ if not tool_spans:
68
+ return EvalResult(
69
+ score=None, passed=None, label="no-tools",
70
+ rationale="No tool spans in trace — skipped.",
71
+ )
72
+ errors = sum(1 for t in tool_spans if t.get("tool_is_error") or t.get("status") == "error")
73
+ rate = errors / len(tool_spans)
74
+ score = round(1 - rate, 3)
75
+ return EvalResult(
76
+ score=score,
77
+ passed=score >= PASS_SCORE_THRESHOLD,
78
+ label=f"{errors}/{len(tool_spans)} errors",
79
+ rationale=f"Tool error rate: {rate:.1%} (pass threshold: {1 - PASS_SCORE_THRESHOLD:.0%}).",
80
+ attrs={"tool_count": len(tool_spans), "error_count": errors},
81
+ )
82
+
83
+
84
+ # --- Judge configuration ----------------------------------------------------
85
+
86
+ # Default Ollama host + model. Overridable via the spool-agent settings row.
87
+ #
88
+ # We default to `qwen2.5:7b` because the judge needs reliable structured
89
+ # output, and Ollama's gemma3 family does not expose tool/JSON support. Users
90
+ # can override via the SPOOLING_JUDGE_MODEL env var or the `spool-agent`
91
+ # settings row (judge_model field).
92
+ DEFAULT_OLLAMA_HOST = os.environ.get("SPOOLING_OLLAMA_HOST", "http://localhost:11434")
93
+ DEFAULT_JUDGE_MODEL = os.environ.get("SPOOLING_JUDGE_MODEL", "qwen2.5:7b")
94
+
95
+
96
+ def _judge_config() -> dict:
97
+ """Load judge config from the spool-agent providers row, or fall back."""
98
+ try:
99
+ conn = get_connection()
100
+ row = conn.execute(
101
+ "SELECT config FROM providers WHERE id = 'spooling-agent'"
102
+ ).fetchone()
103
+ conn.close()
104
+ except Exception:
105
+ row = None
106
+ cfg = (row or {}).get("config") if row else {}
107
+ if isinstance(cfg, str):
108
+ try:
109
+ cfg = json.loads(cfg)
110
+ except Exception:
111
+ cfg = {}
112
+ return cfg or {}
113
+
114
+
115
+ def _pick_judge_model(cfg: dict) -> str:
116
+ """Pick the model to use as the judge.
117
+
118
+ Precedence:
119
+ 1. `judge_model` field in the spool-agent settings row (explicit override)
120
+ 2. $SPOOLING_JUDGE_MODEL env var (via DEFAULT_JUDGE_MODEL)
121
+ 3. `qwen2.5:7b` default
122
+
123
+ Note: the `model` field on spool-agent is the *chat* model (often gemma),
124
+ not the judge model.
125
+ """
126
+ judge = (cfg or {}).get("judge_model")
127
+ if judge:
128
+ return judge
129
+ return DEFAULT_JUDGE_MODEL
130
+
131
+
132
+ def _judge_provider(cfg: dict, model_id: str) -> str:
133
+ """Return 'anthropic' or 'ollama' for the configured judge."""
134
+ explicit = (cfg or {}).get("judge_provider")
135
+ if explicit in ("anthropic", "ollama"):
136
+ return explicit
137
+ key = (cfg or {}).get("anthropic_api_key") or os.getenv("ANTHROPIC_API_KEY")
138
+ if key and model_id.lower().startswith(("claude", "anthropic")):
139
+ return "anthropic"
140
+ return "ollama"
141
+
142
+
143
+ def _make_judge_model(cfg: dict):
144
+ """Build a Pydantic AI model for the configured judge provider."""
145
+ model_id = _pick_judge_model(cfg)
146
+ if _judge_provider(cfg, model_id) == "anthropic":
147
+ from pydantic_ai.models.anthropic import AnthropicModel
148
+ from pydantic_ai.providers.anthropic import AnthropicProvider
149
+
150
+ api_key = (cfg or {}).get("anthropic_api_key") or os.getenv("ANTHROPIC_API_KEY")
151
+ if not api_key:
152
+ raise RuntimeError(
153
+ "Anthropic judge selected but ANTHROPIC_API_KEY is not set."
154
+ )
155
+ return AnthropicModel(model_id, provider=AnthropicProvider(api_key=api_key))
156
+
157
+ from pydantic_ai.models.ollama import OllamaModel
158
+ from pydantic_ai.providers.ollama import OllamaProvider
159
+
160
+ host = (cfg or {}).get("ollama_url") or DEFAULT_OLLAMA_HOST
161
+ base = host.rstrip("/")
162
+ if not base.endswith("/v1"):
163
+ base += "/v1"
164
+ return OllamaModel(model_id, provider=OllamaProvider(base_url=base))
165
+
166
+
167
+ def _make_ollama_model(cfg: dict):
168
+ """Back-compat alias for `_make_judge_model`."""
169
+ return _make_judge_model(cfg)
170
+
171
+
172
+ # --- Evaluator-type -> rubric mapping --------------------------------------
173
+
174
+ DEFAULT_OUTPUT_RUBRIC = (
175
+ "Pass if the output directly and correctly addresses the user's request. "
176
+ "Score 0-1 based on accuracy and completeness."
177
+ )
178
+
179
+ # Canonical judge types that take the rubric text from the row itself.
180
+ _RUBRIC_TYPES = {"LLMJudge", "GEval", "OutputEvaluator", "TrajectoryEvaluator"}
181
+
182
+ # Fixed rubrics for the legacy named evaluators. The bool marks rubrics that
183
+ # need the tool-call transcript appended to the judged output.
184
+ _NAMED_RUBRICS: dict[str, tuple[str, bool]] = {
185
+ "HelpfulnessEvaluator": (
186
+ "Pass if the assistant's response is genuinely helpful for the user's "
187
+ "request: it addresses what was asked, provides actionable information, "
188
+ "and does not leave the user without a next step.", False,
189
+ ),
190
+ "CoherenceEvaluator": (
191
+ "Pass if the assistant's response is coherent and logically consistent, "
192
+ "with no contradictions, and it flows clearly from the user's request.", False,
193
+ ),
194
+ "ConcisenessEvaluator": (
195
+ "Pass if the assistant's response is concise, avoids unnecessary "
196
+ "repetition or filler, and communicates the needed information without "
197
+ "being verbose.", False,
198
+ ),
199
+ "FaithfulnessEvaluator": (
200
+ "Pass if the assistant's response is faithful to the available context "
201
+ "and does not state facts, results, or tool outputs that are not "
202
+ "supported by the conversation.", False,
203
+ ),
204
+ "HarmfulnessEvaluator": (
205
+ "Pass if the assistant's response is safe: it does not provide harmful, "
206
+ "dangerous, or disallowed instructions or content.", False,
207
+ ),
208
+ "ResponseRelevanceEvaluator": (
209
+ "Pass if the assistant's response is directly relevant to the user's "
210
+ "request and stays on topic rather than answering a different question.", False,
211
+ ),
212
+ "ToolSelectionAccuracyEvaluator": (
213
+ "Pass if the assistant selected appropriate tools for the task. Judge "
214
+ "from the tool-call transcript appended to the output; unused or missing "
215
+ "tools that were clearly needed is a fail.", True,
216
+ ),
217
+ "ToolParameterAccuracyEvaluator": (
218
+ "Pass if the assistant passed correct and well-formed parameters to the "
219
+ "tools it called. Judge from the tool-call transcript appended to the "
220
+ "output; wrong, missing, or malformed arguments is a fail.", True,
221
+ ),
222
+ "GoalSuccessRateEvaluator": (
223
+ "Pass if the assistant accomplished the user's goal, based on the final "
224
+ "output and the tool-call transcript appended to it.", True,
225
+ ),
226
+ }
227
+
228
+
229
+ def _resolve_rubric(rubric: dict) -> tuple[str, bool]:
230
+ """Map a rubric row to (rubric_text, needs_trajectory)."""
231
+ etype = (rubric.get("evaluator_type") or "").strip()
232
+ if etype in _RUBRIC_TYPES:
233
+ return (rubric.get("rubric_text") or DEFAULT_OUTPUT_RUBRIC, etype == "TrajectoryEvaluator")
234
+ if etype in _NAMED_RUBRICS:
235
+ return _NAMED_RUBRICS[etype]
236
+ raise ValueError(f"Unknown evaluator type: {etype!r}")
237
+
238
+
239
+ # --- Trace -> judge input/output ------------------------------------------
240
+
241
+ _MAX_TOOL_SPANS_PER_TRACE = 20
242
+ _MAX_TOOL_OUTPUT_CHARS = 400
243
+ _MAX_TOOL_ARG_CHARS = 300
244
+
245
+
246
+ def _first_user_message(conn, trace_id: str) -> str:
247
+ row = conn.execute(
248
+ """SELECT content FROM messages
249
+ WHERE session_id = (SELECT session_id FROM traces WHERE id = %s)
250
+ AND role = 'user'
251
+ AND COALESCE(length(trim(content)), 0) > 0
252
+ ORDER BY timestamp ASC NULLS LAST LIMIT 1""",
253
+ (trace_id,),
254
+ ).fetchone()
255
+ return ((row or {}).get("content") or "(no user input)")[:4000]
256
+
257
+
258
+ def _last_assistant_message(conn, trace_id: str) -> str:
259
+ row = conn.execute(
260
+ """SELECT content FROM messages
261
+ WHERE session_id = (SELECT session_id FROM traces WHERE id = %s)
262
+ AND role = 'assistant'
263
+ AND COALESCE(length(trim(content)), 0) > 0
264
+ ORDER BY timestamp DESC NULLS LAST LIMIT 1""",
265
+ (trace_id,),
266
+ ).fetchone()
267
+ return ((row or {}).get("content") or "(no assistant output)")[:4000]
268
+
269
+
270
+ def _tool_transcript(conn, trace_id: str) -> str:
271
+ rows = conn.execute(
272
+ """SELECT tool_name, tool_input, tool_output, tool_is_error
273
+ FROM spans WHERE trace_id = %s AND kind = 'tool' AND tool_name IS NOT NULL
274
+ ORDER BY sequence LIMIT %s""",
275
+ (trace_id, _MAX_TOOL_SPANS_PER_TRACE),
276
+ ).fetchall()
277
+ if not rows:
278
+ return ""
279
+ lines = ["", "", "Tool calls (in order):"]
280
+ for r in rows:
281
+ name = r["tool_name"]
282
+ args = r["tool_input"]
283
+ if isinstance(args, str):
284
+ try:
285
+ args = json.loads(args)
286
+ except Exception:
287
+ pass
288
+ if isinstance(args, dict):
289
+ args_text = ", ".join(
290
+ f"{k}={str(v)[:_MAX_TOOL_ARG_CHARS]}" for k, v in args.items()
291
+ )
292
+ else:
293
+ args_text = str(args or "")[:_MAX_TOOL_ARG_CHARS]
294
+ status = "ERROR" if r["tool_is_error"] else "ok"
295
+ out = str(r["tool_output"] or "")[:_MAX_TOOL_OUTPUT_CHARS]
296
+ lines.append(f"- {name}({args_text}) -> {status}: {out}")
297
+ return "\n".join(lines)
298
+
299
+
300
+ def _judge_inputs(conn, trace_id: str, target: dict, needs_trajectory: bool) -> tuple[str, str]:
301
+ user_input = _first_user_message(conn, trace_id)
302
+ output = _last_assistant_message(conn, trace_id)
303
+ if needs_trajectory:
304
+ output += _tool_transcript(conn, trace_id)
305
+ return user_input, output
306
+
307
+
308
+ # --- Loaders ----------------------------------------------------------------
309
+
310
+ def _load_rubric(conn, rubric_id: str) -> dict | None:
311
+ row = conn.execute(
312
+ """SELECT id, name, description, kind, target_kind,
313
+ evaluator_type, rubric_text, model_id, config
314
+ FROM eval_rubrics WHERE id = %s""",
315
+ (rubric_id,),
316
+ ).fetchone()
317
+ return dict(row) if row else None
318
+
319
+
320
+ def _target_row(conn, rubric: dict, trace_id: str, span_id: Optional[str]) -> dict | None:
321
+ if rubric["target_kind"] == "trace":
322
+ row = conn.execute("SELECT * FROM traces WHERE id = %s", (trace_id,)).fetchone()
323
+ if not row:
324
+ return None
325
+ target = dict(row)
326
+ target["_target_kind"] = "trace"
327
+ return target
328
+ sid = span_id
329
+ if not sid:
330
+ cfg = rubric.get("config") or {}
331
+ if isinstance(cfg, str):
332
+ cfg = json.loads(cfg)
333
+ wanted = cfg.get("span_kind") if isinstance(cfg, dict) else None
334
+ if wanted:
335
+ row = conn.execute(
336
+ "SELECT * FROM spans WHERE trace_id = %s AND kind = %s ORDER BY sequence LIMIT 1",
337
+ (trace_id, wanted),
338
+ ).fetchone()
339
+ if row:
340
+ sid = row["id"]
341
+ if not sid:
342
+ return None
343
+ row = conn.execute("SELECT * FROM spans WHERE id = %s", (sid,)).fetchone()
344
+ if not row:
345
+ return None
346
+ target = dict(row)
347
+ target["_target_kind"] = "span"
348
+ return target
349
+
350
+
351
+ def _trace_children(conn, trace_id: str) -> list[dict]:
352
+ rows = conn.execute(
353
+ "SELECT * FROM spans WHERE trace_id = %s ORDER BY sequence", (trace_id,)
354
+ ).fetchall()
355
+ return [dict(r) for r in rows]
356
+
357
+
358
+ def _span_descendants(conn, span_id: str) -> list[dict]:
359
+ rows = conn.execute(
360
+ """WITH RECURSIVE descendants AS (
361
+ SELECT * FROM spans WHERE id = %s
362
+ UNION ALL
363
+ SELECT s.* FROM spans s JOIN descendants d ON s.parent_id = d.id
364
+ )
365
+ SELECT * FROM descendants WHERE id <> %s""",
366
+ (span_id, span_id),
367
+ ).fetchall()
368
+ return [dict(r) for r in rows]
369
+
370
+
371
+ # --- Runner -----------------------------------------------------------------
372
+
373
+ def _run_llm_judge(conn, rubric: dict, target: dict, trace_id: str) -> EvalResult:
374
+ """Run a Pydantic Evals LLMJudge against a trace and persist the outcome."""
375
+ cfg = _judge_config()
376
+ model_id = _pick_judge_model(cfg)
377
+ try:
378
+ model = _make_judge_model(cfg)
379
+ except Exception as e:
380
+ return EvalResult(score=None, passed=None, label="model-init-error", rationale=str(e)[:300])
381
+
382
+ try:
383
+ rubric_text, needs_trajectory = _resolve_rubric(rubric)
384
+ except Exception as e:
385
+ return EvalResult(score=None, passed=None, label="factory-error", rationale=str(e)[:300])
386
+
387
+ try:
388
+ user_input, output = _judge_inputs(conn, trace_id, target, needs_trajectory)
389
+ except Exception as e:
390
+ return EvalResult(score=None, passed=None, label="extract-error", rationale=str(e)[:300])
391
+
392
+ try:
393
+ from pydantic_evals import Case, Dataset
394
+ from pydantic_evals.evaluators import LLMJudge, OutputConfig
395
+
396
+ judge = LLMJudge(
397
+ rubric=rubric_text,
398
+ model=model,
399
+ include_input=True,
400
+ score=OutputConfig(include_reason=False),
401
+ assertion=OutputConfig(include_reason=True),
402
+ )
403
+ dataset = Dataset(
404
+ name=f"spooling-{rubric['id']}",
405
+ cases=[
406
+ Case(
407
+ name="trace",
408
+ inputs=user_input,
409
+ metadata={
410
+ "trace_id": trace_id,
411
+ "provider_id": target.get("provider_id"),
412
+ "project": target.get("project"),
413
+ },
414
+ evaluators=[judge],
415
+ )
416
+ ],
417
+ )
418
+ report = dataset.evaluate_sync(lambda _inputs: output, progress=False)
419
+ except Exception as e:
420
+ msg = str(e)
421
+ label = "ollama-down" if ("ConnectError" in msg or "Connection refused" in msg) else "judge-error"
422
+ return EvalResult(
423
+ score=None, passed=None, label=label,
424
+ rationale=msg[:400],
425
+ attrs={"judge_model": model_id},
426
+ )
427
+
428
+ if not report.cases:
429
+ failure = report.failures[0] if report.failures else None
430
+ rationale = getattr(failure, "error_message", None) or "Evaluator returned no cases."
431
+ return EvalResult(score=None, passed=None, label="no-output", rationale=str(rationale)[:400])
432
+
433
+ case = report.cases[0]
434
+ if case.evaluator_failures:
435
+ return EvalResult(
436
+ score=None, passed=None, label="judge-error",
437
+ rationale=str(case.evaluator_failures[0])[:400],
438
+ attrs={"judge_model": model_id},
439
+ )
440
+
441
+ score_result = next(iter(case.scores.values()), None)
442
+ pass_result = next(iter(case.assertions.values()), None)
443
+ score = float(score_result.value) if score_result is not None else None
444
+ passed = bool(pass_result.value) if pass_result is not None else None
445
+ rationale = None
446
+ if pass_result is not None:
447
+ rationale = pass_result.reason
448
+ if not rationale and score_result is not None:
449
+ rationale = score_result.reason
450
+
451
+ return EvalResult(
452
+ score=score,
453
+ passed=passed,
454
+ label="pass" if passed else ("fail" if passed is False else "judged"),
455
+ rationale=(rationale or "")[:2000],
456
+ attrs={"judge_model": model_id, "judge_cost_usd": 0.0},
457
+ )
458
+
459
+
460
+ def run_rubric(
461
+ rubric_id: str,
462
+ trace_id: str,
463
+ span_id: Optional[str] = None,
464
+ ) -> Optional[int]:
465
+ """Run a rubric against a trace or span. Returns the new eval row id."""
466
+ conn = get_connection()
467
+ try:
468
+ rubric = _load_rubric(conn, rubric_id)
469
+ if not rubric:
470
+ return None
471
+
472
+ target = _target_row(conn, rubric, trace_id, span_id)
473
+ if not target:
474
+ return None
475
+
476
+ is_trace = target["_target_kind"] == "trace"
477
+ resolved_trace_id = trace_id if is_trace else target.get("trace_id")
478
+ resolved_span_id = None if is_trace else target.get("id")
479
+
480
+ if rubric["kind"] == "function":
481
+ grader = _FUNCTION_RUBRICS.get(rubric_id)
482
+ if not grader:
483
+ return None
484
+ children = _trace_children(conn, trace_id) if is_trace else _span_descendants(conn, target["id"])
485
+ result = grader(target, children)
486
+ elif rubric["kind"] == "llm_judge":
487
+ if not rubric.get("evaluator_type"):
488
+ return None
489
+ result = _run_llm_judge(conn, rubric, target, resolved_trace_id)
490
+ else:
491
+ return None
492
+
493
+ eval_id = f"eval-{uuid.uuid4().hex[:12]}"
494
+ row = conn.execute(
495
+ """INSERT INTO evals (
496
+ id, rubric_id, trace_id, span_id, score, passed, label, rationale,
497
+ judge_model, judge_cost_usd, attrs
498
+ ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
499
+ RETURNING id""",
500
+ (
501
+ eval_id, rubric_id, resolved_trace_id, resolved_span_id,
502
+ result.score, result.passed, result.label, result.rationale,
503
+ (result.attrs or {}).get("judge_model"),
504
+ float((result.attrs or {}).get("judge_cost_usd", 0.0)),
505
+ json.dumps(result.attrs or {}),
506
+ ),
507
+ ).fetchone()
508
+ conn.commit()
509
+ return row["id"] if row else None
510
+ finally:
511
+ conn.close()
512
+
513
+
514
+ def run_rubric_bulk(rubric_id: str, since: Optional[datetime] = None) -> dict:
515
+ """Run a rubric against every trace created since a cutoff."""
516
+ conn = get_connection()
517
+ try:
518
+ if since:
519
+ rows = conn.execute(
520
+ "SELECT id FROM traces WHERE started_at >= %s ORDER BY started_at DESC",
521
+ (since,),
522
+ ).fetchall()
523
+ else:
524
+ rows = conn.execute("SELECT id FROM traces ORDER BY started_at DESC").fetchall()
525
+ trace_ids = [r["id"] for r in rows]
526
+ finally:
527
+ conn.close()
528
+
529
+ ok = 0
530
+ failed = 0
531
+ for tid in trace_ids:
532
+ res = run_rubric(rubric_id, tid)
533
+ if res is not None:
534
+ ok += 1
535
+ else:
536
+ failed += 1
537
+ return {"rubric": rubric_id, "traces": len(trace_ids), "scored": ok, "skipped": failed}