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
@@ -0,0 +1,465 @@
1
+ """The agent's tools. All of them read; the only way to produce output is `propose`.
2
+
3
+ Every tool runs in a READ ONLY transaction as the modelcall_agent role, with a
4
+ statement timeout. What modelcall_agent can read is set by mod.set_policy:
5
+ tables and columns at level `allow` are granted to it, everything else is
6
+ catalog-only, and objects at `deny` are reported as not existing. The one
7
+ exception is check_relationship, which returns counts only and runs through
8
+ mod._agent_relationship_check (the engine may call it; modelcall_agent may not).
9
+ """
10
+
11
+ import asyncio
12
+ import json
13
+ from contextlib import asynccontextmanager
14
+ from typing import Any, AsyncIterator, Optional
15
+
16
+ import psycopg
17
+ from psycopg import sql
18
+ from psycopg.rows import dict_row
19
+ from psycopg.types.json import Jsonb
20
+
21
+ from .schema import validation_errors
22
+
23
+ MAX_RESULT_CHARS = 8000
24
+ MAX_CELL_CHARS = 200
25
+ QUERY_ROW_LIMIT = 50
26
+ STATEMENT_TIMEOUT_MS = 5000
27
+ RELATIONSHIP_TIMEOUT_MS = 10000
28
+
29
+ MAPPING_FORMAT = """Spec: {"name": "lower_snake_name", "target": "schema.table", "mode": "load",
30
+ "sources": [{"alias": "c", "relation": "schema.table"},
31
+ {"alias": "a", "relation": "schema.other", "join": "left", "on": {"op": "=", "args": ["c.account_id", "a.id"]}}],
32
+ "filter": <expr, optional>,
33
+ "columns": {"target_column": <expr>, ...},
34
+ "key": ["target columns that identify a row (must have a unique constraint)"],
35
+ "order_by": [{"expr": <expr>, "desc": true}] (which source row wins when several map to one key)}
36
+ Expressions: "alias.column" | {"value": literal} | {"fn": name, "args": [...]} | {"op": "=", "args": [a, b]} |
37
+ {"cast": <expr>, "to": "numeric"} | {"case": [{"when": <expr>, "then": <expr>}], "else": <expr>} |
38
+ {"resolve": "domain", "value": <expr>, "context": <expr>} (maps raw values to a master-data code set) |
39
+ {"transform": "name", "value": <expr>} (an approved standardization transform).
40
+ Optional: "delete_missing": true deletes target rows the mapping no longer produces (with "delete_scope":
41
+ {"target_column": literal} to limit it to this source's rows); "incremental": {"expr": "c.updated_at"} reads only
42
+ rows above the last run's highest value (not with delete_missing).
43
+ Functions: lower upper initcap btrim ltrim rtrim length left right substr replace translate regexp_replace
44
+ split_part strpos lpad rpad reverse md5 concat concat_ws coalesce nullif greatest least round trunc abs ceil
45
+ floor to_date to_timestamp to_number to_char date_trunc make_date.
46
+ Operators: + - * / % || = <> < <= > >= like ilike and or not "is null" "is not null" in.
47
+ Parse text dates with to_date(value, 'format') and an explicit format, not a cast, unless the format is ISO."""
48
+
49
+ TOOLS: list[dict] = [
50
+ {
51
+ "name": "list_relations",
52
+ "description": "List the tables and views in scope with their kind, estimated row count, comment and "
53
+ "data policy (allow: values visible; metadata: structure and value-free statistics only).",
54
+ "input_schema": {
55
+ "type": "object",
56
+ "properties": {"schema": {"type": "string", "description": "Limit to one schema in scope"}},
57
+ "additionalProperties": False,
58
+ },
59
+ },
60
+ {
61
+ "name": "describe",
62
+ "description": "Columns (type, nullability, default, comment, policy), keys, foreign keys in both "
63
+ "directions, check constraints and the comment of one table or view.",
64
+ "input_schema": {
65
+ "type": "object",
66
+ "properties": {"relation": {"type": "string", "description": "schema.table"}},
67
+ "required": ["relation"],
68
+ "additionalProperties": False,
69
+ },
70
+ },
71
+ {
72
+ "name": "profile",
73
+ "description": "Statistics for one column: null fraction, distinct values, and (when its policy is allow) "
74
+ "the most common values and range.",
75
+ "input_schema": {
76
+ "type": "object",
77
+ "properties": {"relation": {"type": "string"}, "column": {"type": "string"}},
78
+ "required": ["relation", "column"],
79
+ "additionalProperties": False,
80
+ },
81
+ },
82
+ {
83
+ "name": "sample",
84
+ "description": "A few rows of a table whose policy is allow (only the columns you may see).",
85
+ "input_schema": {
86
+ "type": "object",
87
+ "properties": {
88
+ "relation": {"type": "string"},
89
+ "limit": {"type": "integer", "minimum": 1, "maximum": 20},
90
+ },
91
+ "required": ["relation"],
92
+ "additionalProperties": False,
93
+ },
94
+ },
95
+ {
96
+ "name": "query",
97
+ "description": f"Run one read-only SELECT to check a hypothesis (joins, cardinality, formats). Returns at "
98
+ f"most {QUERY_ROW_LIMIT} rows; times out after {STATEMENT_TIMEOUT_MS // 1000}s. Only "
99
+ "tables and columns with policy allow are readable. Prefer aggregates over raw rows.",
100
+ "input_schema": {
101
+ "type": "object",
102
+ "properties": {"sql": {"type": "string"}},
103
+ "required": ["sql"],
104
+ "additionalProperties": False,
105
+ },
106
+ },
107
+ {
108
+ "name": "check_relationship",
109
+ "description": "Count the rows of one table whose key has no match in another (a candidate foreign key). "
110
+ "Works at any policy and returns counts only, never values. A table of more than 200,000 rows "
111
+ "is counted on a sample of about that many (sampled: true, with estimated_orphans). The "
112
+ "referenced columns need a primary key or unique constraint. Run it before proposing a "
113
+ "relationship, and put the counts in the evidence.",
114
+ "input_schema": {
115
+ "type": "object",
116
+ "properties": {
117
+ "from": {"type": "string", "description": "schema.table that holds the reference"},
118
+ "columns": {"type": "array", "items": {"type": "string"}, "minItems": 1},
119
+ "to": {"type": "string", "description": "schema.table that is referenced"},
120
+ "ref_columns": {"type": "array", "items": {"type": "string"}, "minItems": 1},
121
+ },
122
+ "required": ["from", "columns", "to", "ref_columns"],
123
+ "additionalProperties": False,
124
+ },
125
+ },
126
+ {
127
+ "name": "check_mapping",
128
+ "description": (
129
+ "Dry-run a mapping spec that loads a target table from source tables. Compiles it and returns "
130
+ "counts (source, joined and mapped rows, distinct keys, existing keys), issues (cast failures with "
131
+ "examples, NULLs in required columns, missing foreign-key targets, duplicate keys, join fan-out, "
132
+ "values not yet mapped in a master-data domain) and a sample of output rows. Only data you may "
133
+ "read is used. Fix every error before proposing the mapping.\n" + MAPPING_FORMAT
134
+ ),
135
+ "input_schema": {
136
+ "type": "object",
137
+ "properties": {"spec": {"type": "object", "description": "The mapping spec"}},
138
+ "required": ["spec"],
139
+ "additionalProperties": False,
140
+ },
141
+ },
142
+ {
143
+ "name": "check_transform",
144
+ "description": (
145
+ "Dry-run a standardization transform on real values of a column: an expression over \"$value\" in the "
146
+ "mapping expression language (functions and operators as for check_mapping). Returns how many values it "
147
+ "changes, failures (NULL results, or values not valid for output_type) with examples, and before/after "
148
+ "pairs. Use it before proposing a transform, e.g. to normalize phone numbers, dates or units."
149
+ ),
150
+ "input_schema": {
151
+ "type": "object",
152
+ "properties": {
153
+ "expression": {"description": "Expression over \"$value\", e.g. {\"fn\": \"regexp_replace\", "
154
+ "\"args\": [\"$value\", {\"value\": \"[^0-9+]\"}, {\"value\": \"\"}, "
155
+ "{\"value\": \"g\"}]}"},
156
+ "column": {"type": "string", "description": "schema.table.column whose values to test"},
157
+ "output_type": {"type": "string", "description": "Optional: values must be valid for this type, e.g. date"},
158
+ },
159
+ "required": ["expression", "column"],
160
+ "additionalProperties": False,
161
+ },
162
+ },
163
+ {
164
+ "name": "propose",
165
+ "description": (
166
+ "Record a proposed change for a person to review. This is your only way to change anything. "
167
+ "A new proposal for the same object replaces your earlier one.\n"
168
+ "kind 'comment': a business definition for a table or column; payload "
169
+ "{object: 'table'|'column', schema, table, column (for columns), comment, and optionally synonyms [..], "
170
+ "unit, value_format, examples [..] (a few typical values), categories [..] (for a text column: lower_snake_case "
171
+ "kinds of wrong values found in its values, such as placeholder or location, ending with placeholder and "
172
+ "other; never other columns' names; used by conformance checks)}.\n"
173
+ "kind 'mapping': a mapping spec (see check_mapping) that loads a target table from sources; check it first.\n"
174
+ "kind 'sensitivity': {schema, table, column, class: public|internal|confidential|pii|phi|pci|secret, "
175
+ "policy: allow|metadata|deny (optional; pii/phi/pci/secret default to deny)}. Only with evidence from "
176
+ "names, comments or values.\n"
177
+ "kind 'relationship': an undeclared foreign key {from: schema.table, columns [..], to: schema.table, "
178
+ "ref_columns [..], orphans: <count from check_relationship>, add_constraint: false}. Verify it with "
179
+ "check_relationship first and put the counts in evidence.\n"
180
+ "kind 'quality_rule': {name, schema, table, column, rule: not_null|unique|accepted_values|range|"
181
+ "conformance, params {values | min, max | threshold}, severity: error|warn, description}. A unique rule "
182
+ "over several columns gives columns [..] instead of column. A rule that a NOT NULL, primary key or unique "
183
+ "constraint already enforces is refused: it could never fail.\n"
184
+ "kind 'task': {task: {name, instructions, output (JSON Schema), model?, allow_abstain?}, attach?: "
185
+ "{source: schema.table, input: <SQL expression over its columns>, output: <column or schema.table>}}.\n"
186
+ "kind 'transform': {name, description, expression (over \"$value\"), column (schema.table.column it was "
187
+ "checked on), output_type?}; run check_transform first."
188
+ ),
189
+ "input_schema": {
190
+ "type": "object",
191
+ "properties": {
192
+ "kind": {"type": "string", "enum": ["comment", "mapping", "sensitivity", "relationship",
193
+ "quality_rule", "task", "transform"]},
194
+ "payload": {"type": "object"},
195
+ "rationale": {"type": "string", "description": "Why, and how confident you are"},
196
+ "evidence": {"type": "string", "description": "What you observed that supports it"},
197
+ },
198
+ "required": ["kind", "payload", "rationale"],
199
+ "additionalProperties": False,
200
+ },
201
+ },
202
+ ]
203
+ TOOL_SCHEMAS = {t["name"]: t["input_schema"] for t in TOOLS}
204
+
205
+
206
+ class ToolError(Exception):
207
+ """Reported back to the agent as a failed tool call."""
208
+
209
+
210
+ def _json(value: Any) -> str:
211
+ text = json.dumps(value, ensure_ascii=False, default=str)
212
+ if len(text) > MAX_RESULT_CHARS:
213
+ text = text[:MAX_RESULT_CHARS] + f"... [truncated at {MAX_RESULT_CHARS} characters]"
214
+ return text
215
+
216
+
217
+ def _cell(value: Any) -> Any:
218
+ if value is None or isinstance(value, (bool, int, float)):
219
+ return value
220
+ text = value if isinstance(value, str) else json.dumps(value, default=str) if isinstance(value, (dict, list)) else str(value)
221
+ return text if len(text) <= MAX_CELL_CHARS else text[:MAX_CELL_CHARS] + "..."
222
+
223
+
224
+ class Toolbox:
225
+ def __init__(self, pool, run: dict):
226
+ self.pool = pool
227
+ self.run_id = run["id"]
228
+ self.token = run["lease_token"]
229
+ self.scope = list(run["scope"])
230
+
231
+ # ------------------------------------------------------------ plumbing
232
+ @asynccontextmanager
233
+ async def _readonly(self) -> AsyncIterator[psycopg.AsyncCursor]:
234
+ async with self.pool.connection() as conn:
235
+ async with conn.transaction():
236
+ await conn.execute("SET TRANSACTION READ ONLY")
237
+ await conn.execute("SET LOCAL ROLE modelcall_agent")
238
+ await conn.execute(f"SET LOCAL statement_timeout = {STATEMENT_TIMEOUT_MS}")
239
+ yield conn.cursor(row_factory=dict_row)
240
+
241
+ async def _fetch(self, query: Any, params: Any = None) -> list[dict]:
242
+ async with self._readonly() as cur:
243
+ await cur.execute(query, params)
244
+ return await cur.fetchall()
245
+
246
+ async def _relation(self, name: str) -> dict:
247
+ """Resolve schema.table within scope; denied or out-of-scope objects do not exist."""
248
+ # Resolved in the catalogs, not with to_regclass, which needs USAGE on the schema: at policy
249
+ # metadata modelcall_agent has none, yet may still see the structure.
250
+ rows = await self._fetch(
251
+ """SELECT c.oid, n.nspname AS schema, c.relname AS name, c.relkind,
252
+ mod.policy_level(n.nspname, c.relname) AS level
253
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace,
254
+ parse_ident(%s) AS ident
255
+ WHERE cardinality(ident) = 2 AND n.nspname = ident[1] AND c.relname = ident[2]
256
+ AND c.relkind IN ('r', 'p', 'v', 'm', 'f')""",
257
+ (name,),
258
+ )
259
+ if not rows or rows[0]["schema"] not in self.scope or rows[0]["level"] == "deny":
260
+ raise ToolError(f"no relation {name!r} in scope; use list_relations (names are schema.table)")
261
+ return rows[0]
262
+
263
+ async def _column(self, rel: dict, column: str) -> str:
264
+ rows = await self._fetch(
265
+ """SELECT mod.policy_level(%s, %s, a.attname) AS level FROM pg_attribute a
266
+ WHERE a.attrelid = %s AND a.attname = %s AND a.attnum > 0 AND NOT a.attisdropped""",
267
+ (rel["schema"], rel["name"], rel["oid"], column),
268
+ )
269
+ if not rows or rows[0]["level"] == "deny":
270
+ raise ToolError(f"no column {column!r} in {rel['schema']}.{rel['name']}")
271
+ return rows[0]["level"]
272
+
273
+ # --------------------------------------------------------------- tools
274
+ async def call(self, name: str, arguments: dict) -> tuple[str, bool]:
275
+ """Run a tool. Returns (content, is_error)."""
276
+ if name not in TOOL_SCHEMAS or name == "propose": # propose goes through record_proposal
277
+ return f"unknown tool {name!r}", True
278
+ errors = validation_errors(arguments, TOOL_SCHEMAS[name])
279
+ if errors:
280
+ return "invalid arguments: " + "; ".join(errors), True
281
+ try:
282
+ result = await asyncio.wait_for(getattr(self, name)(**arguments),
283
+ timeout=max(STATEMENT_TIMEOUT_MS * 3, RELATIONSHIP_TIMEOUT_MS * 1.5) / 1000)
284
+ except ToolError as exc:
285
+ return str(exc), True
286
+ except asyncio.TimeoutError:
287
+ return "the tool timed out", True
288
+ except psycopg.errors.InsufficientPrivilege as exc:
289
+ return (f"permission denied ({exc.diag.message_primary or exc}): the rows of tables at policy metadata "
290
+ "are not shared with you. describe, profile and check_relationship work at any policy; sample, "
291
+ "query, check_mapping and check_transform need policy allow, which a person can set."), True
292
+ except psycopg.errors.QueryCanceled:
293
+ return "the query was cancelled at its time limit; narrow it", True
294
+ except psycopg.errors.ReadOnlySqlTransaction:
295
+ return "only read-only queries are allowed", True
296
+ except psycopg.Error as exc:
297
+ return f"database error: {exc.diag.message_primary or exc}", True
298
+ return result if isinstance(result, str) else _json(result), False
299
+
300
+ async def list_relations(self, schema: Optional[str] = None) -> Any:
301
+ if schema is not None and schema not in self.scope:
302
+ raise ToolError(f"schema {schema!r} is not in scope ({', '.join(self.scope)})")
303
+ rows = await self._fetch(
304
+ """SELECT n.nspname || '.' || c.relname AS relation,
305
+ CASE c.relkind WHEN 'r' THEN 'table' WHEN 'p' THEN 'table' WHEN 'v' THEN 'view'
306
+ WHEN 'm' THEN 'materialized view' WHEN 'f' THEN 'foreign table' END AS kind,
307
+ CASE WHEN c.reltuples < 0 THEN NULL ELSE c.reltuples::bigint END AS rows_estimate,
308
+ obj_description(c.oid, 'pg_class') AS comment,
309
+ mod.policy_level(n.nspname, c.relname) AS policy
310
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
311
+ WHERE n.nspname = ANY (%s) AND c.relkind IN ('r', 'p', 'v', 'm', 'f') AND NOT c.relispartition
312
+ AND mod.policy_level(n.nspname, c.relname) <> 'deny'
313
+ ORDER BY 1 LIMIT 300""",
314
+ ([schema] if schema else self.scope,),
315
+ )
316
+ return rows or "no tables or views in scope"
317
+
318
+ async def describe(self, relation: str) -> Any:
319
+ rel = await self._relation(relation)
320
+ columns = await self._fetch(
321
+ """SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type,
322
+ NOT a.attnotnull AS nullable, pg_get_expr(d.adbin, d.adrelid) AS default,
323
+ col_description(a.attrelid, a.attnum) AS comment,
324
+ mod.policy_level(%s, %s, a.attname) AS policy,
325
+ (SELECT array_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e
326
+ WHERE e.enumtypid = a.atttypid) AS enum_values
327
+ FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
328
+ WHERE a.attrelid = %s AND a.attnum > 0 AND NOT a.attisdropped
329
+ ORDER BY a.attnum""",
330
+ (rel["schema"], rel["name"], rel["oid"]),
331
+ )
332
+ visible = [{k: v for k, v in c.items() if v is not None} for c in columns if c["policy"] != "deny"]
333
+ constraints = await self._fetch(
334
+ """SELECT CASE contype WHEN 'p' THEN 'primary_key' WHEN 'u' THEN 'unique'
335
+ WHEN 'f' THEN 'foreign_key' WHEN 'c' THEN 'check' END AS type,
336
+ pg_get_constraintdef(oid) AS definition
337
+ FROM pg_constraint WHERE conrelid = %s AND contype IN ('p', 'u', 'f', 'c')
338
+ ORDER BY contype, conname""",
339
+ (rel["oid"],),
340
+ )
341
+ referenced_by = await self._fetch(
342
+ """SELECT n.nspname || '.' || c.relname AS relation, pg_get_constraintdef(k.oid) AS definition
343
+ FROM pg_constraint k JOIN pg_class c ON c.oid = k.conrelid
344
+ JOIN pg_namespace n ON n.oid = c.relnamespace
345
+ WHERE k.confrelid = %s AND k.contype = 'f' AND n.nspname = ANY (%s)
346
+ AND mod.policy_level(n.nspname, c.relname) <> 'deny'""",
347
+ (rel["oid"], self.scope),
348
+ )
349
+ info = await self._fetch(
350
+ """SELECT obj_description(%s, 'pg_class') AS comment,
351
+ CASE WHEN reltuples < 0 THEN NULL ELSE reltuples::bigint END AS rows_estimate,
352
+ CASE WHEN relkind = 'v' THEN pg_get_viewdef(%s) END AS view_definition
353
+ FROM pg_class WHERE oid = %s""",
354
+ (rel["oid"], rel["oid"], rel["oid"]),
355
+ )
356
+ result = {"relation": f"{rel['schema']}.{rel['name']}", "policy": rel["level"],
357
+ **{k: v for k, v in info[0].items() if v is not None},
358
+ "columns": visible, "constraints": constraints, "referenced_by": referenced_by}
359
+ hidden = len(columns) - len(visible)
360
+ if hidden:
361
+ result["hidden_columns"] = hidden
362
+ return result
363
+
364
+ async def profile(self, relation: str, column: str) -> Any:
365
+ rel = await self._relation(relation)
366
+ level = await self._column(rel, column)
367
+ rows = await self._fetch("SELECT mod._column_stats(%s, %s) AS stats", (rel["oid"], column))
368
+ stats = rows[0]["stats"] or {}
369
+ if stats.get("analyzed"):
370
+ return {"relation": relation, "column": column, "policy": level, **stats}
371
+ if level != "allow":
372
+ return {"relation": relation, "column": column, "policy": level,
373
+ "note": "no statistics yet (the table has not been analyzed), and its values are not shared"}
374
+ ident, table = sql.Identifier(column), sql.Identifier(rel["schema"], rel["name"])
375
+ sample = sql.SQL("(SELECT {c} AS v FROM {t} LIMIT 10000) s").format(c=ident, t=table)
376
+ counts = await self._fetch(sql.SQL(
377
+ "SELECT count(*) AS rows_sampled, count(v) AS non_null, count(DISTINCT v) AS distinct FROM {s}"
378
+ ).format(s=sample))
379
+ top = await self._fetch(sql.SQL(
380
+ "SELECT v::text AS value, count(*) AS count FROM {s} WHERE v IS NOT NULL GROUP BY 1 ORDER BY 2 DESC, 1 LIMIT 10"
381
+ ).format(s=sample))
382
+ return {"relation": relation, "column": column, "policy": level, "analyzed": False,
383
+ "computed_from_first_rows": True, **counts[0],
384
+ "most_common": [{"value": _cell(r["value"]), "count": r["count"]} for r in top]}
385
+
386
+ async def sample(self, relation: str, limit: int = 10) -> Any:
387
+ rel = await self._relation(relation)
388
+ if rel["level"] != "allow":
389
+ raise ToolError(f"{relation} is at policy {rel['level']}: its rows are not shared. Use describe and profile.")
390
+ cols = await self._fetch(
391
+ """SELECT a.attname FROM pg_attribute a
392
+ WHERE a.attrelid = %s AND a.attnum > 0 AND NOT a.attisdropped
393
+ AND mod.policy_level(%s, %s, a.attname) = 'allow'
394
+ ORDER BY a.attnum""",
395
+ (rel["oid"], rel["schema"], rel["name"]),
396
+ )
397
+ if not cols:
398
+ raise ToolError(f"no columns of {relation} are shared")
399
+ names = [c["attname"] for c in cols]
400
+ rows = await self._fetch(sql.SQL("SELECT {cols} FROM {t} LIMIT {n}").format(
401
+ cols=sql.SQL(", ").join(sql.Identifier(n) for n in names),
402
+ t=sql.Identifier(rel["schema"], rel["name"]), n=sql.Literal(limit)))
403
+ return {"relation": relation, "columns": names, "rows": [[_cell(r[n]) for n in names] for r in rows]}
404
+
405
+ async def query(self, **arguments: Any) -> Any: # the argument is named "sql"
406
+ text = arguments["sql"].strip().rstrip(";").strip()
407
+ if not text:
408
+ raise ToolError("sql is empty")
409
+ # Wrapping in a subquery admits exactly one SELECT/VALUES/WITH...SELECT statement.
410
+ wrapped = sql.SQL("SELECT * FROM ({q}) AS modelcall_query LIMIT {n}").format(
411
+ q=sql.SQL(text), n=sql.Literal(QUERY_ROW_LIMIT + 1))
412
+ async with self._readonly() as cur:
413
+ await cur.execute(wrapped)
414
+ rows = await cur.fetchall()
415
+ names = [d.name for d in cur.description or []]
416
+ return {"columns": names, "rows": [[_cell(r[n]) for n in names] for r in rows[:QUERY_ROW_LIMIT]],
417
+ "truncated": len(rows) > QUERY_ROW_LIMIT}
418
+
419
+ async def check_relationship(self, **arguments: Any) -> Any: # one argument is named "from"
420
+ payload = {k: arguments[k] for k in ("from", "columns", "to", "ref_columns")}
421
+ # Not as modelcall_agent: the function reads the tables with its owner's privileges and returns counts only.
422
+ async with self.pool.connection() as conn:
423
+ async with conn.transaction():
424
+ await conn.execute("SET TRANSACTION READ ONLY")
425
+ await conn.execute(f"SET LOCAL statement_timeout = {RELATIONSHIP_TIMEOUT_MS}")
426
+ cur = await conn.execute("SELECT mod._agent_relationship_check(%s::jsonb, %s::text[])",
427
+ (Jsonb(payload), self.scope))
428
+ result = (await cur.fetchone())[0]
429
+ return {"from": payload["from"], "to": payload["to"], **result}
430
+
431
+ async def check_transform(self, expression: Any, column: str, output_type: Optional[str] = None) -> Any:
432
+ parts = column.split(".")
433
+ if len(parts) != 3 or parts[0] not in self.scope:
434
+ raise ToolError(f"column must be schema.table.column in scope ({', '.join(self.scope)})")
435
+ rows = await self._fetch("SELECT mod.check_transform(%s::jsonb, %s, %s) AS result",
436
+ (Jsonb(expression), column, output_type))
437
+ result = rows[0]["result"]
438
+ result.pop("sql", None)
439
+ return result
440
+
441
+ async def check_mapping(self, spec: dict) -> Any:
442
+ rows = await self._fetch("SELECT mod.check_mapping(%s::jsonb, false) AS result", (Jsonb(spec),))
443
+ result = rows[0]["result"]
444
+ result.pop("sql", None) # the compiled statement is for reviewers
445
+ return result
446
+
447
+ async def record_proposal(self, conn: psycopg.AsyncConnection, arguments: dict) -> tuple[str, bool]:
448
+ """Insert the proposal on `conn` (inside the caller's transaction, together with its step)."""
449
+ errors = validation_errors(arguments, TOOL_SCHEMAS["propose"])
450
+ if errors:
451
+ return "invalid arguments: " + "; ".join(errors), True
452
+ evidence = arguments.get("evidence")
453
+ try:
454
+ async with conn.transaction(): # a savepoint: a rejected proposal does not abort the step
455
+ cur = await conn.execute(
456
+ "SELECT mod._propose(%s::bigint, %s::uuid, %s::text, %s::jsonb, %s::text, %s::jsonb)",
457
+ (self.run_id, self.token, arguments["kind"], Jsonb(arguments["payload"]),
458
+ arguments["rationale"], Jsonb({"notes": evidence}) if evidence else None),
459
+ )
460
+ proposal_id = (await cur.fetchone())[0]
461
+ except psycopg.errors.LockNotAvailable:
462
+ raise
463
+ except psycopg.Error as exc:
464
+ return f"proposal not recorded: {exc.diag.message_primary or exc}", True
465
+ return f"proposal {proposal_id} recorded for review", False
modelcall/app.py ADDED
@@ -0,0 +1,137 @@
1
+ import asyncio
2
+ import hmac
3
+ from contextlib import asynccontextmanager
4
+ from typing import Any, Optional
5
+
6
+ from fastapi import Depends, FastAPI, HTTPException, Request
7
+ from fastapi.responses import JSONResponse, PlainTextResponse
8
+ from psycopg_pool import AsyncConnectionPool
9
+ from pydantic import BaseModel, Field, model_validator
10
+
11
+ from . import __version__
12
+ from .inference import Engine, RequestError, Spec
13
+ from .settings import Settings
14
+
15
+
16
+ class SpecIn(BaseModel):
17
+ instructions: str = Field(min_length=1)
18
+ output_schema: Optional[dict[str, Any]] = None
19
+ allow_abstain: bool = False
20
+ model: Optional[str] = None
21
+
22
+
23
+ class RunRequest(BaseModel):
24
+ task: Optional[str] = None
25
+ spec: Optional[SpecIn] = None
26
+ inputs: list[Any] = Field(min_length=1)
27
+ model: Optional[str] = None
28
+ use_cache: bool = True
29
+ caller: Optional[str] = None
30
+ source: Optional[str] = None
31
+
32
+ @model_validator(mode="after")
33
+ def task_or_spec(self) -> "RunRequest":
34
+ if (self.task is None) == (self.spec is None):
35
+ raise ValueError("provide exactly one of 'task' or 'spec'")
36
+ return self
37
+
38
+
39
+ def create_app(settings: Optional[Settings] = None, with_worker: bool = False) -> FastAPI:
40
+ settings = settings or Settings()
41
+ if settings.api_key is None:
42
+ raise RuntimeError("MODELCALL_API_KEY must be set to serve the engine over HTTP")
43
+ expected_key = settings.api_key.get_secret_value().encode()
44
+
45
+ @asynccontextmanager
46
+ async def lifespan(app: FastAPI):
47
+ pool = AsyncConnectionPool(settings.database_url, open=False, kwargs={"autocommit": True})
48
+ await pool.open()
49
+ app.state.engine = Engine(settings, pool)
50
+ stop = asyncio.Event()
51
+ background = []
52
+ if with_worker:
53
+ from .worker import runners
54
+
55
+ background = [asyncio.create_task(runner.run(stop)) for runner in runners(app.state.engine)]
56
+ try:
57
+ yield
58
+ finally:
59
+ stop.set()
60
+ await asyncio.gather(*background)
61
+ await pool.close()
62
+
63
+ app = FastAPI(title="modelcall engine", version=__version__, lifespan=lifespan)
64
+
65
+ @app.exception_handler(RequestError)
66
+ async def request_error(_request: Request, exc: RequestError) -> JSONResponse:
67
+ return JSONResponse(status_code=exc.status, content={"detail": {"code": exc.code, "message": exc.message}})
68
+
69
+ def authenticate(request: Request) -> None:
70
+ header = request.headers.get("authorization", "")
71
+ key = header[7:] if header.lower().startswith("bearer ") else request.headers.get("x-api-key", "")
72
+ if not key or not hmac.compare_digest(key.encode(), expected_key):
73
+ raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "missing or invalid API key"})
74
+
75
+ @app.get("/v1/health")
76
+ async def health(request: Request) -> dict:
77
+ try:
78
+ await request.app.state.engine.setting("default_model")
79
+ database = True
80
+ except Exception:
81
+ database = False
82
+ return {"status": "ok" if database else "degraded", "database": database, "version": __version__}
83
+
84
+ @app.get("/metrics", dependencies=[Depends(authenticate)], response_class=PlainTextResponse)
85
+ async def metrics(request: Request) -> str:
86
+ """Prometheus text format: queue depth and lag, calls, failures, spend."""
87
+ engine: Engine = request.app.state.engine
88
+ rows = await engine._fetchall("SELECT name, labels, value FROM mod.metrics() ORDER BY name")
89
+ return render_metrics(rows)
90
+
91
+ @app.post("/v1/run", dependencies=[Depends(authenticate)])
92
+ async def run(body: RunRequest, request: Request) -> dict:
93
+ if len(body.inputs) > settings.max_inputs:
94
+ raise RequestError(422, "too_many_inputs", f"at most {settings.max_inputs} inputs per request")
95
+ engine: Engine = request.app.state.engine
96
+ spec = await engine.load_task(body.task) if body.task else Spec(**body.spec.model_dump())
97
+ results = await engine.run(spec, body.inputs, model=body.model, use_cache=body.use_cache,
98
+ caller=body.caller, source=body.source or "api")
99
+ return {"results": [r.to_dict() for r in results]}
100
+
101
+ from .review import mount_review
102
+
103
+ mount_review(app, settings, authenticate)
104
+ return app
105
+
106
+
107
+ HELP = {
108
+ "modelcall_queue_items": ("gauge", "Work items of attached tasks by state"),
109
+ "modelcall_queue_lag_seconds": ("gauge", "Age of the oldest pending work item"),
110
+ "modelcall_attachment_spend_usd_total": ("counter", "Cumulative spend of an attachment"),
111
+ "modelcall_attachment_calls_total": ("counter", "Cumulative model calls of an attachment"),
112
+ "modelcall_calls_24h": ("gauge", "Model calls in the last 24 hours by status"),
113
+ "modelcall_cache_hits_24h": ("gauge", "Cache hits in the last 24 hours"),
114
+ "modelcall_spend_usd_24h": ("gauge", "Spend in the last 24 hours"),
115
+ "modelcall_agent_runs": ("gauge", "Agent runs by state"),
116
+ "modelcall_agent_spend_usd_total": ("counter", "Cumulative agent spend"),
117
+ "modelcall_unresolved_values": ("gauge", "Values waiting in the resolution queue by state"),
118
+ "modelcall_provider_batches": ("gauge", "Provider batches by state"),
119
+ }
120
+
121
+
122
+ def render_metrics(rows: list[dict]) -> str:
123
+ lines: list[str] = []
124
+ seen: set[str] = set()
125
+ for row in rows:
126
+ name = row["name"]
127
+ if name not in seen:
128
+ seen.add(name)
129
+ kind, text = HELP.get(name, ("gauge", name))
130
+ lines += [f"# HELP {name} {text}", f"# TYPE {name} {kind}"]
131
+ labels = ",".join(f'{k}="{_escape_label(v)}"' for k, v in sorted((row["labels"] or {}).items()))
132
+ lines.append(f"{name}{{{labels}}} {float(row['value'])}" if labels else f"{name} {float(row['value'])}")
133
+ return "\n".join(lines) + "\n"
134
+
135
+
136
+ def _escape_label(value: Any) -> str:
137
+ return str(value).replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"')