modelcall 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.
Files changed (57) hide show
  1. modelcall/__init__.py +3 -0
  2. modelcall/__main__.py +203 -0
  3. modelcall/agent.py +322 -0
  4. modelcall/agent_tools.py +465 -0
  5. modelcall/app.py +137 -0
  6. modelcall/batches.py +134 -0
  7. modelcall/checker.py +534 -0
  8. modelcall/cli.py +636 -0
  9. modelcall/doctor.py +113 -0
  10. modelcall/evaluator.py +174 -0
  11. modelcall/export.py +244 -0
  12. modelcall/inference.py +710 -0
  13. modelcall/matcher.py +276 -0
  14. modelcall/mcp_server.py +218 -0
  15. modelcall/migrate.py +120 -0
  16. modelcall/profiling.py +186 -0
  17. modelcall/providers/__init__.py +20 -0
  18. modelcall/providers/anthropic.py +223 -0
  19. modelcall/providers/base.py +89 -0
  20. modelcall/providers/fake.py +140 -0
  21. modelcall/providers/openai_compat.py +345 -0
  22. modelcall/resolver.py +303 -0
  23. modelcall/review.py +354 -0
  24. modelcall/schema.py +107 -0
  25. modelcall/serve.py +15 -0
  26. modelcall/settings.py +50 -0
  27. modelcall/sql/bridge/http.sql +53 -0
  28. modelcall/sql/bridge/plpython3u.sql +56 -0
  29. modelcall/sql/install.sql +26 -0
  30. modelcall/sql/migrations/0001_core.sql +589 -0
  31. modelcall/sql/migrations/0002_tasks.sql +941 -0
  32. modelcall/sql/migrations/0003_agent.sql +644 -0
  33. modelcall/sql/migrations/0004_master_data.sql +585 -0
  34. modelcall/sql/migrations/0005_mappings.sql +900 -0
  35. modelcall/sql/migrations/0006_providers.sql +32 -0
  36. modelcall/sql/migrations/0007_ledger.sql +735 -0
  37. modelcall/sql/migrations/0008_evaluation.sql +919 -0
  38. modelcall/sql/migrations/0009_semantics.sql +852 -0
  39. modelcall/sql/migrations/0010_conformance.sql +779 -0
  40. modelcall/sql/migrations/0011_standardization.sql +540 -0
  41. modelcall/sql/migrations/0012_entities.sql +686 -0
  42. modelcall/sql/migrations/0013_check_controls.sql +107 -0
  43. modelcall/sql/migrations/0014_preview_categories.sql +37 -0
  44. modelcall/sql/migrations/0015_agent_and_rules.sql +385 -0
  45. modelcall/sql/migrations/0016_check_population.sql +82 -0
  46. modelcall/sql/migrations/0017_rename_to_modelcall.sql +125 -0
  47. modelcall/sql/migrations/0018_routing.sql +260 -0
  48. modelcall/sql/migrations/0019_measured_routing.sql +207 -0
  49. modelcall/sql/migrations/0020_watch_costs_categories.sql +271 -0
  50. modelcall/text.py +45 -0
  51. modelcall/worker.py +307 -0
  52. modelcall-0.1.0.dist-info/METADATA +257 -0
  53. modelcall-0.1.0.dist-info/RECORD +57 -0
  54. modelcall-0.1.0.dist-info/WHEEL +5 -0
  55. modelcall-0.1.0.dist-info/entry_points.txt +2 -0
  56. modelcall-0.1.0.dist-info/licenses/LICENSE +202 -0
  57. modelcall-0.1.0.dist-info/top_level.txt +1 -0
modelcall/cli.py ADDED
@@ -0,0 +1,636 @@
1
+ """One-shot commands: `modelcall run`, `check`, `annotate`, `classify`, `evaluate`, `models`, `export`, `review`,
2
+ `mcp`.
3
+
4
+ Everything runs in this process and exits: it installs or upgrades the schema
5
+ if needed, does the work, and prints a report. There is no service to deploy
6
+ and no bridge to install; a connection string and a model are enough. A model
7
+ is given as provider:model (anthropic:claude-opus-5-5, openai:gpt-5-mini,
8
+ ollama:llama3.2, bedrock:..., vertex:..., foundry:...) or as the name of an
9
+ existing model profile.
10
+ """
11
+
12
+ import asyncio
13
+ import os
14
+ import re
15
+ import sys
16
+ import time
17
+ from typing import Any, Callable, Optional
18
+
19
+ import psycopg
20
+ from psycopg.rows import dict_row
21
+ from psycopg.types.json import Jsonb
22
+
23
+
24
+ class CliError(SystemExit):
25
+ def __init__(self, message: str):
26
+ super().__init__(f"modelcall: {message}")
27
+
28
+
29
+ def database_error(exc: psycopg.Error) -> str:
30
+ """An error the database raised, as a line (and its hint) to print instead of a traceback."""
31
+ diag = getattr(exc, "diag", None)
32
+ message = (diag.message_primary if diag else None) or (str(exc).strip().splitlines() or [type(exc).__name__])[0]
33
+ hint = diag.message_hint if diag else None
34
+ return f"modelcall: {message.removeprefix('modelcall: ')}" + (f"\n hint: {hint}" if hint else "")
35
+
36
+
37
+ # ------------------------------------------------------------------ plumbing
38
+ def database_url(given: Optional[str]) -> str:
39
+ if given:
40
+ return given
41
+ url = os.environ.get("MODELCALL_DATABASE_URL")
42
+ if not url:
43
+ try:
44
+ from .settings import DatabaseSettings
45
+
46
+ url = DatabaseSettings().database_url
47
+ except Exception:
48
+ url = None
49
+ if not url:
50
+ raise CliError("give a connection string (postgresql://...) or set MODELCALL_DATABASE_URL")
51
+ return url
52
+
53
+
54
+ def connect(url: str) -> psycopg.Connection:
55
+ try:
56
+ return psycopg.connect(url, autocommit=True)
57
+ except psycopg.OperationalError as exc:
58
+ raise CliError(f"cannot connect: {str(exc).strip()}")
59
+
60
+
61
+ def ensure_installed(url: str, out: Callable[[str], None] = print) -> None:
62
+ from .migrate import migrate
63
+
64
+ try:
65
+ ran = migrate(url)
66
+ except psycopg.errors.InsufficientPrivilege as exc:
67
+ raise CliError(f"installing modelcall needs CREATE on the database and CREATEROLE ({exc.diag.message_primary}); "
68
+ "run `modelcall migrate` once as such a role, or `modelcall doctor` for details")
69
+ if ran:
70
+ out(f"Installed modelcall schema mod ({', '.join(ran)}).")
71
+
72
+
73
+ def parse_model(spec: str) -> tuple[str, str, str, dict]:
74
+ """provider:model -> (profile name, provider, model, params)."""
75
+ if spec == "fake":
76
+ return "cli_fake", "fake", "fake-1", {}
77
+ provider, _, model = spec.partition(":")
78
+ if not model:
79
+ raise CliError(f"model {spec!r}: use provider:model, e.g. anthropic:claude-opus-5-5 or ollama:llama3.2")
80
+ params: dict = {}
81
+ if provider == "ollama":
82
+ host = os.environ.get("OLLAMA_HOST", "http://localhost:11434").rstrip("/")
83
+ if not host.startswith("http"):
84
+ host = "http://" + host
85
+ provider, params = "openai", {"base_url": host + "/v1", "max_concurrency": 2}
86
+ elif provider not in ("anthropic", "openai", "bedrock", "vertex", "foundry", "fake"):
87
+ raise CliError(f"unknown provider {provider!r}")
88
+ name = "cli_" + re.sub(r"[^a-z0-9]+", "_", f"{spec.split(':')[0]}_{model}".lower()).strip("_")
89
+ return name[:60], provider, model, params
90
+
91
+
92
+ def profile_for(conn: psycopg.Connection, spec: str) -> str:
93
+ """The profile named, or one created (or updated) from provider:model."""
94
+ if ":" not in spec and spec != "fake":
95
+ if not conn.execute("SELECT EXISTS (SELECT FROM mod.models WHERE name = %s)", (spec,)).fetchone()[0]:
96
+ raise CliError(f"no model profile {spec!r}; give provider:model to create one")
97
+ return spec
98
+ name, provider, model, params = parse_model(spec)
99
+ conn.execute("""INSERT INTO mod.models (name, provider, model, params, description)
100
+ VALUES (%s, %s, %s, %s, 'created by the modelcall command line')
101
+ ON CONFLICT (name) DO UPDATE SET provider = EXCLUDED.provider, model = EXCLUDED.model,
102
+ params = mod.models.params || EXCLUDED.params""",
103
+ (name, provider, model, Jsonb(params)))
104
+ return name
105
+
106
+
107
+ TIER_KEYS = ("model_low", "model_medium", "model_high")
108
+
109
+
110
+ def model_tiers(conn: psycopg.Connection) -> Optional[dict[str, str]]:
111
+ """{"low": profile, "medium": ..., "high": ...} when all three are set (routing is on), else None."""
112
+ found = dict(conn.execute("SELECT key, value FROM mod.settings WHERE key = ANY (%s) AND value <> ''",
113
+ (list(TIER_KEYS),)).fetchall())
114
+ return {k.removeprefix("model_"): found[k] for k in TIER_KEYS} if len(found) == len(TIER_KEYS) else None
115
+
116
+
117
+ def ensure_model(conn: psycopg.Connection, spec: Optional[str], out: Callable[[str], None] = print) -> Optional[str]:
118
+ """The model profile to use: the one named, one created from provider:model, or the default.
119
+ None when no model is named and the tiers are set: the router chooses."""
120
+ default = conn.execute("SELECT nullif(value, '') FROM mod.settings WHERE key = 'default_model'").fetchone()[0]
121
+ if spec is None:
122
+ if model_tiers(conn):
123
+ return None
124
+ if default:
125
+ return default
126
+ if os.environ.get("ANTHROPIC_API_KEY"):
127
+ spec = "anthropic:claude-opus-5-5"
128
+ else:
129
+ raise CliError("no model: pass --model (e.g. anthropic:claude-opus-5-5, ollama:llama3.2), or set "
130
+ "the model tiers with `modelcall models`")
131
+ name = profile_for(conn, spec)
132
+ if not default and not model_tiers(conn):
133
+ conn.execute("UPDATE mod.settings SET value = %s WHERE key = 'default_model'", (name,))
134
+ out(f"Model profile {name} ({model_label(conn, name)}) is now the default.")
135
+ return name
136
+
137
+
138
+ def model_label(conn: psycopg.Connection, name: Optional[str]) -> str:
139
+ """'provider model' for a profile; for None, the three tiers the router chooses between."""
140
+ if name is None:
141
+ tiers = model_tiers(conn) or {}
142
+ return "the tier the low model picks (" + ", ".join(
143
+ f"{tier}: {model_label(conn, profile)}" for tier, profile in tiers.items()) + ")"
144
+ row = conn.execute("SELECT provider || ' ' || model FROM mod.models WHERE name = %s", (name,)).fetchone()
145
+ return row[0] if row else f"{name} (no such profile)"
146
+
147
+
148
+ def drain(url: str, out: Callable[[str], None] = print) -> dict:
149
+ """Runs every queue in this process until nothing is left."""
150
+ from .serve import loop_factory
151
+ from .settings import Settings
152
+
153
+ async def go() -> dict:
154
+ from psycopg_pool import AsyncConnectionPool
155
+
156
+ from .inference import Engine
157
+ from .worker import drain_all
158
+
159
+ settings = Settings(database_url=url)
160
+ pool = AsyncConnectionPool(url, open=False, kwargs={"autocommit": True}, min_size=1, max_size=8)
161
+ await pool.open()
162
+ try:
163
+ return await drain_all(Engine(settings, pool))
164
+ finally:
165
+ await pool.close()
166
+
167
+ return asyncio.run(go(), loop_factory=loop_factory)
168
+
169
+
170
+ def wait_for_checks(url: str, names: list[str], out: Callable[[str], None] = print, poll_seconds: float = 2.0) -> None:
171
+ """Waits for checks of these columns that another worker (modelcall serve --worker) is still running."""
172
+ told = False
173
+ while True:
174
+ with connect(url) as conn:
175
+ left = conn.execute("SELECT count(*) FROM mod.check_runs WHERE column_name = ANY (%s) "
176
+ "AND state IN ('queued', 'running')", (names,)).fetchone()[0]
177
+ if not left:
178
+ return
179
+ if not told:
180
+ out(f"Waiting for {left} check(s) another worker is running...")
181
+ told = True
182
+ time.sleep(poll_seconds)
183
+
184
+
185
+ def table(rows: list[dict], columns: list[str], out: Callable[[str], None] = print, empty: str = "(none)") -> None:
186
+ if not rows:
187
+ out(empty)
188
+ return
189
+ cells = [[_fmt(r.get(c)) for c in columns] for r in rows]
190
+ widths = [max(len(c), *(len(row[i]) for row in cells)) for i, c in enumerate(columns)]
191
+ out(" ".join(c.ljust(w) for c, w in zip(columns, widths)))
192
+ out(" ".join("-" * w for w in widths))
193
+ for row in cells:
194
+ out(" ".join(v.ljust(w) for v, w in zip(row, widths)))
195
+
196
+
197
+ UNPRICED_NOTE = ("Cost unknown: the model profile has no prices. Add params.pricing to it to record costs "
198
+ "(`modelcall models` shows which profiles have them).")
199
+
200
+
201
+ def money(value: Any, digits: int = 4) -> str:
202
+ """Dollars, or "unknown" when a call was made on a model profile without prices."""
203
+ return "unknown" if value is None else f"${float(value):.{digits}f}"
204
+
205
+
206
+ def report_unfinished(conn: psycopg.Connection, since: Any, out: Callable[[str], None] = print) -> int:
207
+ """Prints, per task, the work items processed since `since` that did not finish, with the latest error.
208
+ Returns how many there were."""
209
+ problems = rows(conn, """
210
+ SELECT a.task, a.source::text AS source,
211
+ count(*) FILTER (WHERE w.state = 'failed') AS failed,
212
+ count(*) FILTER (WHERE w.state = 'pending') AS retrying,
213
+ (array_agg(w.error_code || ': ' || w.error ORDER BY w.updated_at DESC))[1] AS error
214
+ FROM mod.work w JOIN mod.attachments a ON a.id = w.attachment_id
215
+ WHERE w.updated_at >= %s AND w.error IS NOT NULL AND w.state IN ('failed', 'pending')
216
+ GROUP BY 1, 2 ORDER BY 1, 2""", (since,))
217
+ for p in problems:
218
+ parts = [f"{p['failed']} failed"] * bool(p["failed"]) + [f"{p['retrying']} will retry"] * bool(p["retrying"])
219
+ out(f"{p['task']} on {p['source']}: {' and '.join(parts)}. Last error: {p['error']}")
220
+ return sum(p["failed"] + p["retrying"] for p in problems)
221
+
222
+
223
+ def _fmt(value: Any) -> str:
224
+ if value is None:
225
+ return ""
226
+ if isinstance(value, float):
227
+ return f"{value:.4g}"
228
+ text = str(value)
229
+ return text if len(text) <= 60 else text[:57] + "..."
230
+
231
+
232
+ def category_shares(violate_pct: Any, by_category: Optional[dict]) -> list[tuple[str, float]]:
233
+ """Each category's share of all rows, largest first. by_category counts rows of the checked
234
+ population (a sample when the column was sampled), so it is scaled to violate_pct."""
235
+ counts = {k: float(v) for k, v in (by_category or {}).items() if v}
236
+ total = sum(counts.values())
237
+ if not total or violate_pct is None:
238
+ return []
239
+ return sorted(((k, float(violate_pct) * v / total) for k, v in counts.items()), key=lambda kv: -kv[1])
240
+
241
+
242
+ def rows(conn: psycopg.Connection, query: str, params: Any = None) -> list[dict]:
243
+ return conn.cursor(row_factory=dict_row).execute(query, params).fetchall()
244
+
245
+
246
+ # ------------------------------------------------------------------ commands
247
+ def cmd_run(args, out: Callable[[str], None] = print) -> int:
248
+ url = database_url(args.database)
249
+ ensure_installed(url, out)
250
+ with connect(url) as conn:
251
+ if args.model:
252
+ ensure_model(conn, args.model, out)
253
+ for statement in args.sql or []:
254
+ cur = conn.execute(statement)
255
+ if cur.description:
256
+ result = [dict(zip([d.name for d in cur.description], r)) for r in cur.fetchall()]
257
+ table(result, [d.name for d in cur.description], out)
258
+ since = conn.execute("SELECT clock_timestamp()").fetchone()[0]
259
+ counts = drain(url, out)
260
+ with connect(url) as conn:
261
+ unfinished = report_unfinished(conn, since, out)
262
+ processed = ", ".join(f"{n} {what}" for what, n in counts.items() if n)
263
+ if unfinished:
264
+ out(f"Processed {processed}; {unfinished} work item(s) did not finish (above).")
265
+ return 2
266
+ out(f"Done: {processed}" if processed else "Done: nothing was queued.")
267
+ return 0
268
+
269
+
270
+ def cmd_check(args, out: Callable[[str], None] = print, confirm: Callable[[str], bool] = None) -> int:
271
+ url = database_url(args.database)
272
+ ensure_installed(url, out)
273
+ with connect(url) as conn:
274
+ model = ensure_model(conn, args.model, out)
275
+ provider = model_label(conn, model)
276
+ candidates = rows(conn, "SELECT * FROM mod.check_candidates(%s)", (args.schema,))
277
+ if not candidates and not conn.execute("SELECT to_regnamespace(%s) IS NOT NULL", (args.schema,)).fetchone()[0]:
278
+ raise CliError(f"no schema {args.schema}")
279
+ if args.table:
280
+ candidates = [c for c in candidates if c["column_name"].split(".")[1] in args.table]
281
+ if args.column:
282
+ wanted = set(args.column)
283
+ candidates = [c for c in candidates if c["column_name"].split(".")[-1] in wanted or c["column_name"] in wanted]
284
+ for c in candidates: # named explicitly: check text columns even if the heuristics would skip them
285
+ if not c["included"] and not c["reason"].startswith(("policy", "not text")):
286
+ c["included"], c["reason"] = True, "named on the command line"
287
+ shareable = [c for c in candidates if not c["included"] and c["reason"].startswith("policy metadata")]
288
+ chosen = [c for c in candidates if c["included"]]
289
+ skipped = [c for c in candidates if not c["included"] and c not in shareable]
290
+
291
+ if shareable:
292
+ out(f"These columns' values are not shared with modelcall yet (policy metadata). Checking them sends their "
293
+ f"distinct values to {provider}:")
294
+ for c in shareable:
295
+ distinct = (f"about {_fmt(c['distinct_estimate'])} distinct values" if c["distinct_estimate"] is not None
296
+ else "distinct values not known until the table is analyzed")
297
+ out(f" {c['column_name']} ({c['data_type']}, {distinct})")
298
+ ask = confirm or (lambda q: input(q).strip().lower() in ("y", "yes"))
299
+ if args.allow_values or args.yes or (sys.stdin.isatty() and ask("Share them for this check? [y/N] ")):
300
+ for c in shareable:
301
+ conn.execute("SELECT mod.set_policy(%s, 'allow')", (c["column_name"],))
302
+ chosen += shareable
303
+ else:
304
+ skipped += shareable
305
+ out("Not shared: rerun with --allow-values to include them.")
306
+ if skipped:
307
+ out("\nSkipped:")
308
+ table([{"column": c["column_name"], "why": c["reason"]} for c in skipped], ["column", "why"], out)
309
+ if not chosen:
310
+ out("\nNothing to check.")
311
+ return 0
312
+ out(f"\nChecking {len(chosen)} column(s) with {provider}: " + ", ".join(c["column_name"] for c in chosen))
313
+ out("Ctrl+C cancels these checks; from SQL, SELECT mod.cancel_checks() stops them (a running engine "
314
+ "worker processes the same queue).")
315
+ for c in chosen:
316
+ conn.execute("SELECT mod.check_column(%s, reference => %s, model => %s)", (c["column_name"], args.reference, model))
317
+
318
+ names = [c["column_name"] for c in chosen]
319
+ try:
320
+ drain(url, out)
321
+ wait_for_checks(url, names, out)
322
+ except KeyboardInterrupt:
323
+ with connect(url) as conn:
324
+ cancelled = sum(conn.execute("SELECT mod.cancel_check(%s)", (c["column_name"],)).fetchone()[0]
325
+ for c in chosen)
326
+ out(f"\nCancelled {cancelled} check(s). Values already judged are kept and reused by the next check.")
327
+ return 130
328
+
329
+ with connect(url) as conn:
330
+ report = rows(conn, """SELECT column_name AS "column", rows, conform_pct, violate_pct, unknown_pct,
331
+ distinct_values AS "distinct", definition_status AS definition, verification,
332
+ state, reason
333
+ FROM mod.conformance WHERE column_name = ANY (%s) ORDER BY violate_pct DESC NULLS LAST""",
334
+ (names,))
335
+ out("\nConformance (share of rows whose value belongs to what the column is defined to hold):")
336
+ table(report, ["column", "rows", "conform_pct", "violate_pct", "unknown_pct", "distinct", "definition",
337
+ "verification"], out)
338
+ for r in report:
339
+ if r["state"] in ("skipped", "failed"):
340
+ out(f" {r['column']}: {r['state']}: {r['reason']}")
341
+ for r in report:
342
+ if r["violate_pct"]:
343
+ cats = conn.execute("SELECT by_category FROM mod.conformance WHERE column_name = %s",
344
+ (r["column"],)).fetchone()[0] or {}
345
+ summary = ", ".join(f"{k} {round(share)}%" for k, share in category_shares(r["violate_pct"], cats))
346
+ out(f"\n{r['column']}: {r['violate_pct']}% of rows violate ({summary})")
347
+ table(rows(conn, "SELECT value, rows, category, rationale FROM mod.violations(%s) LIMIT %s",
348
+ (r["column"], args.top)), ["value", "rows", "category", "rationale"], out)
349
+ written, categorized = conn.execute(
350
+ """SELECT count(*) FILTER (WHERE coalesce(payload ->> 'before', '') = ''),
351
+ count(*) FILTER (WHERE coalesce(payload ->> 'before', '') <> '')
352
+ FROM mod.proposals WHERE kind = 'comment' AND status = 'proposed' AND target = ANY (%s)""",
353
+ (["column:" + n for n in names],)).fetchone()
354
+ if written:
355
+ out(f"\n{written} definition(s) were written for columns that had none; the results above use them "
356
+ f"provisionally. Review them with: modelcall review --kind comment")
357
+ if categorized:
358
+ out(f"\n{categorized} column(s) were judged against their existing descriptions, with proposed lists of "
359
+ f"what does not belong in them. Review them with: modelcall review --kind comment")
360
+ out("\nResults are unverified until audited: SELECT * FROM mod.audit_sample('<column>'), then "
361
+ "mod.judge_value(...) to label them.")
362
+ if any(r["state"] == "failed" for r in report):
363
+ return 2 # a check could not run (no credit, no definition, model errors)
364
+ if args.fail_under is not None and any((r["conform_pct"] or 0) < args.fail_under for r in report
365
+ if r["state"] != "skipped"):
366
+ return 1
367
+ return 0
368
+
369
+
370
+ ANNOTATE_GOAL = (
371
+ "Write business definitions for {relations} and every one of their columns{only}. For text columns that hold "
372
+ "a kind of thing, include conformance categories.\n\n"
373
+ "Below is a profile of each, computed from the data before this run; values appear only where the data policy "
374
+ "shares them. Read it before you write. State the units, scales, allowed values, formats and conventions the "
375
+ "values show, and what a value means. Use describe, sample or query for what the profile leaves open. Keep "
376
+ "each definition to one to three short sentences, meaning first. Where the data cannot settle a meaning, say "
377
+ "so in the rationale rather than in the definition.\n\n"
378
+ "{profiles}")
379
+
380
+
381
+ def cmd_annotate(args, out: Callable[[str], None] = print, confirm: Callable[[str], bool] = None) -> int:
382
+ from . import profiling
383
+
384
+ url = database_url(args.database)
385
+ ensure_installed(url, out)
386
+ with connect(url) as conn:
387
+ # The agent is not routed: without --model it runs on default_model, else the medium tier.
388
+ model = ensure_model(conn, args.model, out) or conn.execute(
389
+ """SELECT coalesce((SELECT nullif(value, '') FROM mod.settings WHERE key = 'default_model'),
390
+ (SELECT value FROM mod.settings WHERE key = 'model_medium'))""").fetchone()[0]
391
+ provider = model_label(conn, model)
392
+ rels = profiling.relations(conn, args.schema)
393
+ if not rels:
394
+ raise CliError(f"no tables or views in schema(s) {', '.join(args.schema)}")
395
+ only: dict = {} # relation -> objects still to describe, with --changed
396
+ if args.changed:
397
+ for c in rows(conn, """SELECT schema_name || '.' || table_name AS relation,
398
+ coalesce(column_name, '(table)') AS object, status FROM mod.semantics_status
399
+ WHERE schema_name = ANY (%s) AND status IN ('new', 'changed') ORDER BY 1, 2""",
400
+ (args.schema,)):
401
+ only.setdefault(c["relation"], []).append(f"{c['object']} ({c['status']})")
402
+ if not only:
403
+ out("Every object already has a current definition.")
404
+ return 0
405
+
406
+ hidden = sorted({r["schema"] for r in rels for c in r["columns"] if c["level"] == "metadata"})
407
+ if hidden:
408
+ out(f"Values in {', '.join(hidden)} are not shared with modelcall (policy metadata), so definitions there are "
409
+ f"written from names, types and statistics. Reading the values sends a profile of each column (its most "
410
+ f"common values and range) and a few sample rows to {provider}.")
411
+ ask = confirm or (lambda q: input(q).strip().lower() in ("y", "yes"))
412
+ if args.allow_values or args.yes or (sys.stdin.isatty() and ask("Share values for these definitions? [y/N] ")):
413
+ for schema in hidden:
414
+ conn.execute("SELECT mod.set_policy(%s, 'allow')", (schema,))
415
+ rels = profiling.relations(conn, args.schema)
416
+ else:
417
+ out("Not shared: rerun with --allow-values to let modelcall read them.")
418
+
419
+ profiled = profiling.profile_relations(conn, args.schema, set(only) if args.changed else None)
420
+ runs = []
421
+ for batch in profiling.batches(profiled):
422
+ names = [f"{r['schema']}.{r['name']}" for r, _ in batch]
423
+ listed = [o for n in names for o in (f"{n}.{x}" for x in only.get(n, []))]
424
+ goal = ANNOTATE_GOAL.format(
425
+ relations=", ".join(names), profiles="\n\n".join(text for _, text in batch),
426
+ only=(" that are new or changed since they were described: " + "; ".join(listed[:200])) if listed else "")
427
+ scope = sorted({r["schema"] for r, _ in batch})
428
+ runs.append(conn.execute("SELECT mod.agent(%s, %s, %s, %s)", (goal, scope, model, args.max_steps)).fetchone()[0])
429
+ out(f"Profiled {len(profiled)} tables and views; {len(runs)} agent run(s) queued with {model}.")
430
+ drain(url, out)
431
+ with connect(url) as conn:
432
+ status = rows(conn, """SELECT id AS run, state, stop_reason, steps, proposals, round(cost_usd, 4) AS usd, error
433
+ FROM mod.agent_status WHERE id = ANY (%s) ORDER BY id""", (runs,))
434
+ unpriced = any(r["usd"] is None and r["steps"] for r in status)
435
+ table([{**r, "usd": "unknown" if r["usd"] is None and r["steps"] else r["usd"]} for r in status],
436
+ ["run", "state", "stop_reason", "steps", "proposals", "usd"], out)
437
+ for r in status:
438
+ if r["error"]:
439
+ out(f" run {r['run']}: {r['error']}")
440
+ total = None if unpriced else sum(float(r["usd"] or 0) for r in status)
441
+ out(f"{sum(r['proposals'] or 0 for r in status)} proposals, {money(total)}")
442
+ if unpriced:
443
+ out(UNPRICED_NOTE)
444
+ if args.export:
445
+ from . import export
446
+
447
+ text = "\n".join(export.export_sql_proposals(conn, run) for run in runs) if args.export == "sql" else \
448
+ export.export_dbt(conn, args.schema) if args.export == "dbt" else export.export_json(conn, args.schema)
449
+ write_output(text, args.out, out)
450
+ else:
451
+ out("\nReview with: modelcall review --kind comment (or modelcall export --format sql --run <run> for a pull request)")
452
+ return 0
453
+
454
+
455
+ def cmd_classify(args, out: Callable[[str], None] = print) -> int:
456
+ url = database_url(args.database)
457
+ ensure_installed(url, out)
458
+ labels = [x.strip() for x in args.labels.split(",") if x.strip()]
459
+ if len(labels) < 2:
460
+ raise CliError("--labels needs at least two labels, comma-separated")
461
+ task = args.task or re.sub(r"[^a-z0-9_]+", "_", f"classify_{args.table}_{args.output}".lower())[:60]
462
+ notes: list[str] = [] # printed once the setup below has committed
463
+ with connect(url) as conn:
464
+ with conn.transaction(): # all of the setup or, if a step fails, none of it
465
+ model = ensure_model(conn, args.model, notes.append)
466
+ conn.execute("SELECT mod.create_task(%s, %s, mod.enum_of(VARIADIC %s), %s, true, pack => %s, promote => true)",
467
+ (task, args.instructions or "Classify the input into exactly one of the labels.", labels, model,
468
+ args.pack))
469
+ attached = conn.execute("SELECT watch FROM mod.attachments WHERE task = %s AND source = %s::regclass",
470
+ (task, args.table)).fetchone()
471
+ if attached is None:
472
+ est = rows(conn, "SELECT rows, calls, est_usd, sends_columns, provider FROM mod.estimate(%s, %s::regclass, %s)",
473
+ (task, args.table, args.input))[0]
474
+ notes.append(f"{est['rows']} rows in {est['calls']} calls to {est['provider']}"
475
+ + (f", about ${est['est_usd']}" if est["est_usd"] is not None else "")
476
+ + f"; sends columns: {', '.join(est['sends_columns'])}")
477
+ conn.execute("SELECT mod.attach(%s, %s::regclass, %s, %s, watch => %s, mode => %s)",
478
+ (task, args.table, args.input, args.output, args.watch, "batch" if args.batch else "online"))
479
+ elif args.watch and not attached[0]: # attached earlier without --watch; also queues rows changed since
480
+ conn.execute("SELECT mod.set_watch(%s, %s::regclass)", (task, args.table))
481
+ notes.append(f"Now watching {args.table}: new and changed rows are queued for the worker.")
482
+ else:
483
+ conn.execute("SELECT mod.backfill(%s, %s::regclass)", (task, args.table))
484
+ since = conn.execute("SELECT clock_timestamp()").fetchone()[0]
485
+ for note in notes:
486
+ out(note)
487
+ if args.batch:
488
+ out("Submitted to the provider's batch API; results arrive within 24 hours. Run `modelcall run` later "
489
+ "(or keep `modelcall worker` running) to collect them.")
490
+ drain(url, out)
491
+ with connect(url) as conn:
492
+ if "." not in args.output:
493
+ from psycopg import sql
494
+
495
+ query = sql.SQL("SELECT {c}::text AS label, count(*) AS rows FROM {t} GROUP BY 1 ORDER BY 2 DESC").format(
496
+ c=sql.Identifier(args.output), t=sql.Identifier(*args.table.split(".", 1)))
497
+ table(conn.cursor(row_factory=dict_row).execute(query).fetchall(), ["label", "rows"], out)
498
+ job = rows(conn, "SELECT items, done, failed, abstained, calls, cache_hits, cost_usd FROM mod.job_status "
499
+ "WHERE task = %s ORDER BY job DESC LIMIT 1", (task,))
500
+ unpriced = any(j["cost_usd"] is None and j["calls"] for j in job)
501
+ table([{**j, "cost_usd": "unknown" if j["cost_usd"] is None else j["cost_usd"]} for j in job],
502
+ ["items", "done", "failed", "abstained", "calls", "cache_hits", "cost_usd"], out)
503
+ if unpriced:
504
+ out(UNPRICED_NOTE)
505
+ unfinished = report_unfinished(conn, since, out)
506
+ return 2 if unfinished else 0
507
+
508
+
509
+ def cmd_evaluate(args, out: Callable[[str], None] = print) -> int:
510
+ url = database_url(args.database)
511
+ ensure_installed(url, out)
512
+ measurement = None
513
+ with connect(url) as conn:
514
+ if args.route: # the three tiers, and the subject's route from the result
515
+ if args.models:
516
+ raise CliError("--route evaluates the low, medium and high tiers; leave out --models")
517
+ try:
518
+ measurement = conn.execute("SELECT mod.measure_route(%s)", (args.subject,)).fetchone()[0]
519
+ except psycopg.errors.RaiseException as exc:
520
+ raise CliError(exc.diag.message_primary.removeprefix("modelcall: "))
521
+ runs = sorted({int(r) for r in conn.execute(
522
+ "SELECT runs FROM mod.route_measurements WHERE id = %s", (measurement,)).fetchone()[0].values()})
523
+ else:
524
+ models = [ensure_model(conn, m, out) for m in args.models.split(",")] if args.models else None
525
+ runs = [r["run_id"] for r in rows(conn, "SELECT * FROM mod.evaluate(%s, %s)", (args.subject, models))]
526
+ drain(url, out)
527
+ with connect(url) as conn:
528
+ table(rows(conn, """SELECT model, n, correct, abstained, invalid, accuracy, precision, usd_per_1k, p50_ms, state
529
+ FROM mod.eval_summary WHERE run_id = ANY (%s) ORDER BY accuracy DESC NULLS LAST""", (runs,)),
530
+ ["model", "n", "correct", "abstained", "invalid", "accuracy", "precision", "usd_per_1k", "p50_ms", "state"],
531
+ out)
532
+ out("Failures: SELECT * FROM mod.eval_failures(<run_id>); runs: " + ", ".join(map(str, runs)))
533
+ if measurement is not None:
534
+ m = rows(conn, """SELECT m.state, m.tier, m.note, m.tolerance, m.models, r.tier AS route, r.decided_by
535
+ FROM mod.route_measurements m
536
+ LEFT JOIN mod.routes r ON r.kind = m.kind AND r.subject = m.subject
537
+ WHERE m.id = %s""", (measurement,))[0]
538
+ if m["state"] == "decided" and m["note"]:
539
+ out(f"\nMeasured best: the {m['tier']} tier ({m['models'][m['tier']]}), but {m['decided_by']} set the "
540
+ f"{m['route']} tier by hand, which is kept. Clear it with SELECT mod.set_route('{args.subject}', NULL).")
541
+ elif m["state"] == "decided":
542
+ out(f"\nRouted to the {m['tier']} tier ({m['models'][m['tier']]}): the least expensive within "
543
+ f"{float(m['tolerance']) * 100:g} points of the best accuracy.")
544
+ else:
545
+ out(f"\nThe measurement {m['state']}: {m['note'] or 'still running in another worker'}; the route is unchanged.")
546
+ return 0
547
+
548
+
549
+ def write_output(text: str, path: Optional[str], out: Callable[[str], None] = print) -> None:
550
+ if path and path != "-":
551
+ with open(path, "w", encoding="utf-8", newline="\n") as f:
552
+ f.write(text)
553
+ out(f"Wrote {path}")
554
+ else:
555
+ sys.stdout.write(text)
556
+
557
+
558
+ def cmd_models(args, out: Callable[[str], None] = print) -> int:
559
+ """Sets the default model and the low, medium and high tiers, then shows profiles, tiers and routes."""
560
+ url = database_url(args.database)
561
+ ensure_installed(url, out)
562
+ with connect(url) as conn:
563
+ given = {"default_model": args.default, "model_low": args.low, "model_medium": args.medium,
564
+ "model_high": args.high}
565
+ if args.no_tiers: # tiers given on the same line are kept
566
+ given.update({key: "" for key in TIER_KEYS if given[key] is None})
567
+ for key, spec in given.items():
568
+ if spec is not None:
569
+ conn.execute("UPDATE mod.settings SET value = %s WHERE key = %s",
570
+ (profile_for(conn, spec) if spec else "", key))
571
+ out("Model profiles:")
572
+ table(rows(conn, """SELECT name, provider, model, CASE WHEN params ? 'pricing' THEN 'yes' ELSE '' END AS priced
573
+ FROM mod.models ORDER BY name"""), ["name", "provider", "model", "priced"], out)
574
+ settings = dict(conn.execute("SELECT key, value FROM mod.settings WHERE key = ANY (%s)",
575
+ (["default_model", *TIER_KEYS],)).fetchall())
576
+ tiers = model_tiers(conn)
577
+ out("")
578
+ if tiers:
579
+ out("Routing is on: work that names no model runs on the tier the low model picks for it.")
580
+ table([{"tier": t, "profile": p, "model": model_label(conn, p)} for t, p in tiers.items()],
581
+ ["tier", "profile", "model"], out)
582
+ if settings.get("default_model"):
583
+ out(f"default_model {settings['default_model']} is used only by agent runs that name no model.")
584
+ routes = rows(conn, """SELECT kind, subject, tier, decided_by, left(reason, 80) AS reason FROM mod.routes
585
+ ORDER BY decided_at DESC LIMIT 25""")
586
+ out("\nRoutes (newest first; clear one with SELECT mod.set_route('<subject>', NULL)):")
587
+ table(routes, ["kind", "subject", "tier", "decided_by", "reason"], out, empty="(none yet)")
588
+ else:
589
+ default = settings.get("default_model")
590
+ out(f"Routing is off. Work that names no model runs on default_model: {default or '(not set)'}.")
591
+ missing = [k.removeprefix("model_") for k in TIER_KEYS if not settings.get(k)]
592
+ if len(missing) < len(TIER_KEYS):
593
+ out(f"Set the {' and '.join(missing)} tier{'s' if len(missing) > 1 else ''} as well to turn it on.")
594
+ else:
595
+ out("Turn it on with --low, --medium and --high.")
596
+ return 0
597
+
598
+
599
+ def cmd_export(args, out: Callable[[str], None] = print) -> int:
600
+ from . import export
601
+
602
+ url = database_url(args.database)
603
+ schemas = args.schema or None
604
+ with connect(url) as conn:
605
+ if args.format == "sql":
606
+ text = export.export_sql_proposals(conn, args.run) if args.run or args.approved \
607
+ else export.export_sql_semantics(conn, schemas)
608
+ elif args.format == "dbt":
609
+ text = export.export_dbt(conn, schemas, as_sources=args.sources)
610
+ if args.out and args.out != "-":
611
+ macro = os.path.join(os.path.dirname(os.path.abspath(args.out)), "modelcall_conformance.sql")
612
+ with open(macro, "w", encoding="utf-8", newline="\n") as f:
613
+ f.write(export.CONFORMANCE_TEST)
614
+ out(f"Wrote {macro} (the generic test behind conformance rules; put it in tests/generic/)")
615
+ else:
616
+ text = export.export_json(conn, schemas)
617
+ write_output(text, args.out, out)
618
+ return 0
619
+
620
+
621
+ def cmd_review(args, out: Callable[[str], None] = print) -> int:
622
+ from .review import terminal_review
623
+
624
+ url = database_url(args.database)
625
+ with connect(url) as conn:
626
+ counts = terminal_review(conn, run=args.run, kind=args.kind, status=args.status, write=out,
627
+ search=args.search, domain=args.domain)
628
+ out("Reviewed: " + ", ".join(f"{n} {k}" for k, n in counts.items() if n))
629
+ return 0
630
+
631
+
632
+ def cmd_mcp(args, out: Callable[[str], None] = print) -> int:
633
+ from .mcp_server import serve
634
+
635
+ serve(database_url(args.database))
636
+ return 0