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.
- modelcall/__init__.py +3 -0
- modelcall/__main__.py +203 -0
- modelcall/agent.py +322 -0
- modelcall/agent_tools.py +465 -0
- modelcall/app.py +137 -0
- modelcall/batches.py +134 -0
- modelcall/checker.py +534 -0
- modelcall/cli.py +636 -0
- modelcall/doctor.py +113 -0
- modelcall/evaluator.py +174 -0
- modelcall/export.py +244 -0
- modelcall/inference.py +710 -0
- modelcall/matcher.py +276 -0
- modelcall/mcp_server.py +218 -0
- modelcall/migrate.py +120 -0
- modelcall/profiling.py +186 -0
- modelcall/providers/__init__.py +20 -0
- modelcall/providers/anthropic.py +223 -0
- modelcall/providers/base.py +89 -0
- modelcall/providers/fake.py +140 -0
- modelcall/providers/openai_compat.py +345 -0
- modelcall/resolver.py +303 -0
- modelcall/review.py +354 -0
- modelcall/schema.py +107 -0
- modelcall/serve.py +15 -0
- modelcall/settings.py +50 -0
- modelcall/sql/bridge/http.sql +53 -0
- modelcall/sql/bridge/plpython3u.sql +56 -0
- modelcall/sql/install.sql +26 -0
- modelcall/sql/migrations/0001_core.sql +589 -0
- modelcall/sql/migrations/0002_tasks.sql +941 -0
- modelcall/sql/migrations/0003_agent.sql +644 -0
- modelcall/sql/migrations/0004_master_data.sql +585 -0
- modelcall/sql/migrations/0005_mappings.sql +900 -0
- modelcall/sql/migrations/0006_providers.sql +32 -0
- modelcall/sql/migrations/0007_ledger.sql +735 -0
- modelcall/sql/migrations/0008_evaluation.sql +919 -0
- modelcall/sql/migrations/0009_semantics.sql +852 -0
- modelcall/sql/migrations/0010_conformance.sql +779 -0
- modelcall/sql/migrations/0011_standardization.sql +540 -0
- modelcall/sql/migrations/0012_entities.sql +686 -0
- modelcall/sql/migrations/0013_check_controls.sql +107 -0
- modelcall/sql/migrations/0014_preview_categories.sql +37 -0
- modelcall/sql/migrations/0015_agent_and_rules.sql +385 -0
- modelcall/sql/migrations/0016_check_population.sql +82 -0
- modelcall/sql/migrations/0017_rename_to_modelcall.sql +125 -0
- modelcall/sql/migrations/0018_routing.sql +260 -0
- modelcall/sql/migrations/0019_measured_routing.sql +207 -0
- modelcall/sql/migrations/0020_watch_costs_categories.sql +271 -0
- modelcall/text.py +45 -0
- modelcall/worker.py +307 -0
- modelcall-0.1.0.dist-info/METADATA +257 -0
- modelcall-0.1.0.dist-info/RECORD +57 -0
- modelcall-0.1.0.dist-info/WHEEL +5 -0
- modelcall-0.1.0.dist-info/entry_points.txt +2 -0
- modelcall-0.1.0.dist-info/licenses/LICENSE +202 -0
- modelcall-0.1.0.dist-info/top_level.txt +1 -0
modelcall/profiling.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Column profiles for writing definitions: what the data holds, read before a model describes it.
|
|
2
|
+
|
|
3
|
+
Statistics come from mod._column_stats (pg_stats), which shows most common values and ranges only for columns
|
|
4
|
+
at policy allow. A column at allow without statistics (a view, or a table never analyzed) is profiled from its
|
|
5
|
+
first rows instead. Values of columns at metadata are never read here: their profile is null fraction and
|
|
6
|
+
distinct count only, so a profile never shares more than the data policy does.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from typing import Any, Optional
|
|
11
|
+
|
|
12
|
+
import psycopg
|
|
13
|
+
from psycopg import sql
|
|
14
|
+
from psycopg.rows import dict_row
|
|
15
|
+
|
|
16
|
+
SAMPLE_ROWS = 2_000
|
|
17
|
+
STATEMENT_TIMEOUT = "20s"
|
|
18
|
+
MAX_VALUE_CHARS = 60
|
|
19
|
+
MOST_COMMON = 6
|
|
20
|
+
MIN_FREQUENCY = 0.01 # a value under 1% of rows is not "most common" in any useful sense
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def relations(conn: psycopg.Connection, schemas: list[str]) -> list[dict]:
|
|
24
|
+
"""Tables, views and materialized views in the schemas, with their columns and policies (deny left out)."""
|
|
25
|
+
rows = conn.cursor(row_factory=dict_row).execute("""
|
|
26
|
+
SELECT c.oid, n.nspname AS schema, c.relname AS name,
|
|
27
|
+
CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END AS kind,
|
|
28
|
+
CASE WHEN c.reltuples < 0 THEN NULL ELSE c.reltuples::bigint END AS rows_estimate,
|
|
29
|
+
mod.policy_level(n.nspname, c.relname) AS level,
|
|
30
|
+
coalesce(jsonb_agg(jsonb_build_object('name', a.attname, 'type', format_type(a.atttypid, a.atttypmod),
|
|
31
|
+
'not_null', a.attnotnull,
|
|
32
|
+
'level', mod.policy_level(n.nspname, c.relname, a.attname))
|
|
33
|
+
ORDER BY a.attnum) FILTER (WHERE a.attnum IS NOT NULL), '[]') AS columns
|
|
34
|
+
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
35
|
+
LEFT JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
|
|
36
|
+
WHERE n.nspname = ANY (%s) AND c.relkind IN ('r', 'p', 'v', 'm', 'f') AND NOT c.relispartition
|
|
37
|
+
AND mod.policy_level(n.nspname, c.relname) <> 'deny'
|
|
38
|
+
GROUP BY c.oid, n.nspname, c.relname, c.relkind, c.reltuples
|
|
39
|
+
ORDER BY n.nspname, c.relname""", (schemas,)).fetchall()
|
|
40
|
+
for r in rows:
|
|
41
|
+
r["columns"] = [c for c in r["columns"] if c["level"] != "deny"]
|
|
42
|
+
return rows
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _short(value: Any) -> str:
|
|
46
|
+
text = str(value).replace("\n", " ")
|
|
47
|
+
return text if len(text) <= MAX_VALUE_CHARS else text[:MAX_VALUE_CHARS - 1] + "…"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
NO_VALUES_TYPES = ("tsvector", "tsquery", "bytea") # their values say nothing a definition needs
|
|
51
|
+
TEXT_TYPES = ("text", "character", "json", "xml")
|
|
52
|
+
WIDE_BYTES = 500 # wider columns (documents, HTML) are read from a few rows only, and cut short
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _read_rows(conn: psycopg.Connection, rel: dict, columns: list[str], limit: int) -> dict[str, list]:
|
|
56
|
+
"""The first rows of some columns, as text cut to 200 characters: one query per relation."""
|
|
57
|
+
cols = sql.SQL(", ").join(sql.SQL("left({c}::text, 200)").format(c=sql.Identifier(c)) for c in columns)
|
|
58
|
+
with conn.transaction():
|
|
59
|
+
conn.execute("SET LOCAL transaction_read_only = on")
|
|
60
|
+
conn.execute(f"SET LOCAL statement_timeout = '{STATEMENT_TIMEOUT}'")
|
|
61
|
+
rows = conn.execute(sql.SQL("SELECT {cols} FROM {t} LIMIT {n}").format(
|
|
62
|
+
cols=cols, t=sql.Identifier(rel["schema"], rel["name"]), n=sql.Literal(limit))).fetchall()
|
|
63
|
+
return {c: [r[i] for r in rows] for i, c in enumerate(columns)}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _from_values(values: list, wide: bool) -> dict:
|
|
67
|
+
"""Null fraction, distinct count and most common values of a column's first rows."""
|
|
68
|
+
present = [v for v in values if v is not None]
|
|
69
|
+
out: dict = {"rows_read": len(values), "null_fraction": 1 - len(present) / len(values) if values else None}
|
|
70
|
+
if not present:
|
|
71
|
+
return out
|
|
72
|
+
counts = Counter(present)
|
|
73
|
+
if not wide:
|
|
74
|
+
out["distinct"] = len(counts)
|
|
75
|
+
top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
|
|
76
|
+
frequent = [(v, n / len(present)) for v, n in top if n > 1 and n / len(present) >= MIN_FREQUENCY]
|
|
77
|
+
if frequent and not wide:
|
|
78
|
+
out["most_common"] = frequent[:MOST_COMMON]
|
|
79
|
+
else:
|
|
80
|
+
out["examples"] = [v for v, _ in top[:3]]
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _from_stats(stats: dict, column: dict) -> tuple[dict, bool]:
|
|
85
|
+
"""A column's profile from pg_stats, and whether its values are too wide to read in bulk."""
|
|
86
|
+
out = {k: stats[k] for k in ("null_fraction", "distinct", "distinct_fraction") if k in stats}
|
|
87
|
+
if column["level"] != "allow" or column["type"].startswith(NO_VALUES_TYPES):
|
|
88
|
+
return out, False
|
|
89
|
+
common = [(m["value"], m["frequency"]) for m in stats.get("most_common") or []]
|
|
90
|
+
# Postgres leaves values over 1 kB out of its statistics, so long text can look narrow: judge by the values too
|
|
91
|
+
wide = (stats.get("avg_width_bytes") or 0) > WIDE_BYTES or any(len(str(v)) > 100 for v, _ in common)
|
|
92
|
+
frequent = [(v, f) for v, f in common if f >= MIN_FREQUENCY]
|
|
93
|
+
if frequent and not wide:
|
|
94
|
+
out["most_common"] = frequent[:MOST_COMMON]
|
|
95
|
+
elif common and not wide: # near-unique: a most-common list says nothing, a few values say what they look like
|
|
96
|
+
out["examples"] = [v for v, _ in common[:3]]
|
|
97
|
+
if stats.get("histogram_min") is not None and not column["type"].startswith(TEXT_TYPES):
|
|
98
|
+
out["min"], out["max"] = stats["histogram_min"], stats.get("histogram_max")
|
|
99
|
+
return out, wide
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def profile_relation(conn: psycopg.Connection, rel: dict) -> dict[str, dict]:
|
|
103
|
+
"""What the data says about each column of one relation, within its policy."""
|
|
104
|
+
profiles, wide, unanalyzed, need_rows = {}, set(), False, []
|
|
105
|
+
for col in rel["columns"]:
|
|
106
|
+
stats = conn.execute("SELECT mod._column_stats(%s, %s)", (rel["oid"], col["name"])).fetchone()[0] or {}
|
|
107
|
+
profiles[col["name"]], is_wide = _from_stats(stats, col)
|
|
108
|
+
if is_wide:
|
|
109
|
+
wide.add(col["name"])
|
|
110
|
+
if col["level"] != "allow" or col["type"].startswith(NO_VALUES_TYPES):
|
|
111
|
+
continue
|
|
112
|
+
p = profiles[col["name"]]
|
|
113
|
+
if not stats.get("analyzed"):
|
|
114
|
+
unanalyzed = True
|
|
115
|
+
need_rows.append(col["name"])
|
|
116
|
+
elif not (p.get("most_common") or p.get("examples") or p.get("min") is not None):
|
|
117
|
+
need_rows.append(col["name"])
|
|
118
|
+
if need_rows: # a view, a table never analyzed, or values too varied for statistics: read a few rows
|
|
119
|
+
try:
|
|
120
|
+
read = _read_rows(conn, rel, need_rows, SAMPLE_ROWS if unanalyzed else 20)
|
|
121
|
+
except psycopg.Error as exc: # a slow view: describe it without values
|
|
122
|
+
for c in need_rows:
|
|
123
|
+
profiles[c]["error"] = exc.diag.message_primary or str(exc)
|
|
124
|
+
else:
|
|
125
|
+
for c, values in read.items():
|
|
126
|
+
got = _from_values(values, c in wide or not unanalyzed)
|
|
127
|
+
if not unanalyzed: # statistics already gave the counts; keep only what they lacked
|
|
128
|
+
got = {k: v for k, v in got.items() if k == "examples"}
|
|
129
|
+
profiles[c].update(got)
|
|
130
|
+
return profiles
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def describe_profile(rel: dict, profiles: dict[str, dict]) -> str:
|
|
134
|
+
"""One relation as plain text for a prompt: a line per column with what its values show."""
|
|
135
|
+
head = f"{rel['schema']}.{rel['name']} ({rel['kind']}" + (
|
|
136
|
+
f", about {rel['rows_estimate']:,} rows" if rel.get("rows_estimate") else "") + ")"
|
|
137
|
+
lines = [head]
|
|
138
|
+
for col in rel["columns"]:
|
|
139
|
+
p = profiles.get(col["name"], {})
|
|
140
|
+
parts = [col["type"] + (", not null" if col["not_null"] else "")]
|
|
141
|
+
if p.get("null_fraction"):
|
|
142
|
+
nf = 100 * p["null_fraction"]
|
|
143
|
+
parts.append(f"{nf:.0f}% null" if nf >= 1 else f"{nf:.1g}% null")
|
|
144
|
+
if p.get("distinct") is not None:
|
|
145
|
+
parts.append(f"{int(p['distinct']):,} distinct" +
|
|
146
|
+
(f" in its first {p['rows_read']:,} rows" if p.get("rows_read") else ""))
|
|
147
|
+
elif p.get("distinct_fraction") is not None:
|
|
148
|
+
parts.append(f"distinct in {100 * p['distinct_fraction']:.0f}% of rows")
|
|
149
|
+
if p.get("most_common"):
|
|
150
|
+
parts.append("most common: " + ", ".join(f"{_short(v)} ({100 * f:.0f}%)" for v, f in p["most_common"]))
|
|
151
|
+
if p.get("error"):
|
|
152
|
+
parts.append(f"values not read ({_short(p['error'])})")
|
|
153
|
+
if p.get("min") is not None:
|
|
154
|
+
parts.append(f"range {_short(p['min'])} to {_short(p['max'])}")
|
|
155
|
+
if p.get("examples"):
|
|
156
|
+
parts.append("e.g. " + "; ".join(_short(v) for v in p["examples"]))
|
|
157
|
+
if col["level"] != "allow":
|
|
158
|
+
parts.append("values not shared (policy metadata)")
|
|
159
|
+
lines.append(f" {col['name']}: " + "; ".join(parts))
|
|
160
|
+
return "\n".join(lines)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def profile_relations(conn: psycopg.Connection, schemas: list[str],
|
|
164
|
+
only: Optional[set] = None) -> list[tuple[dict, str]]:
|
|
165
|
+
"""(relation, its profile as text) for every relation in the schemas, or those in `only` (schema.table)."""
|
|
166
|
+
out = []
|
|
167
|
+
for rel in relations(conn, schemas):
|
|
168
|
+
if only is not None and f"{rel['schema']}.{rel['name']}" not in only:
|
|
169
|
+
continue
|
|
170
|
+
out.append((rel, describe_profile(rel, profile_relation(conn, rel))))
|
|
171
|
+
return out
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def batches(profiled: list[tuple[dict, str]], max_columns: int = 40) -> list[list[tuple[dict, str]]]:
|
|
175
|
+
"""Relations grouped for one agent run each: small ones together, up to max_columns columns per run."""
|
|
176
|
+
groups: list[list[tuple[dict, str]]] = []
|
|
177
|
+
size = 0
|
|
178
|
+
for item in profiled:
|
|
179
|
+
n = len(item[0]["columns"]) + 1
|
|
180
|
+
if groups and size + n <= max_columns and groups[-1][0][0]["schema"] == item[0]["schema"]:
|
|
181
|
+
groups[-1].append(item)
|
|
182
|
+
size += n
|
|
183
|
+
else:
|
|
184
|
+
groups.append([item])
|
|
185
|
+
size = n
|
|
186
|
+
return groups
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from .base import Completion, Provider, ProviderError, ToolCall, Turn
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def create_provider(provider: str, model: str, params: dict, timeout: float) -> Provider:
|
|
5
|
+
if provider in ("anthropic", "bedrock", "vertex", "foundry"):
|
|
6
|
+
from .anthropic import AnthropicProvider
|
|
7
|
+
|
|
8
|
+
return AnthropicProvider(model, params, timeout, platform=provider)
|
|
9
|
+
if provider == "openai":
|
|
10
|
+
from .openai_compat import OpenAICompatProvider
|
|
11
|
+
|
|
12
|
+
return OpenAICompatProvider(model, params, timeout)
|
|
13
|
+
if provider == "fake":
|
|
14
|
+
from .fake import FakeProvider
|
|
15
|
+
|
|
16
|
+
return FakeProvider(model, params, timeout)
|
|
17
|
+
raise ProviderError("config_error", f"unknown provider {provider!r}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
__all__ = ["Completion", "Provider", "ProviderError", "ToolCall", "Turn", "create_provider"]
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from typing import Any, Awaitable, Callable, Optional
|
|
3
|
+
|
|
4
|
+
import anthropic
|
|
5
|
+
|
|
6
|
+
from .base import Completion, ProviderError, ToolCall, Turn, api_key_from_env
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
CLAUDE_PLATFORMS = ("anthropic", "bedrock", "vertex", "foundry") # same Messages API content blocks
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _client(platform: str, params: dict, timeout: float) -> Any:
|
|
13
|
+
"""The SDK client for a platform. The engine owns retries, so SDK retries are off."""
|
|
14
|
+
common = {"max_retries": 0, "timeout": timeout}
|
|
15
|
+
try:
|
|
16
|
+
if platform == "bedrock":
|
|
17
|
+
# Amazon Bedrock's Messages API (Mantle). Credentials: the AWS chain
|
|
18
|
+
# (environment, profile, instance or task role), or a Bedrock API key.
|
|
19
|
+
return anthropic.AsyncAnthropicBedrockMantle(
|
|
20
|
+
aws_region=params.get("aws_region"), aws_profile=params.get("aws_profile"),
|
|
21
|
+
api_key=api_key_from_env(params), base_url=params.get("base_url"), **common)
|
|
22
|
+
if platform == "vertex":
|
|
23
|
+
# Google Cloud Vertex AI. Credentials: Application Default Credentials.
|
|
24
|
+
return anthropic.AsyncAnthropicVertex(
|
|
25
|
+
project_id=params.get("project_id"), region=params.get("region", "global"),
|
|
26
|
+
base_url=params.get("base_url"), **common)
|
|
27
|
+
if platform == "foundry":
|
|
28
|
+
# Microsoft Foundry: resource name (or base_url) and an API key.
|
|
29
|
+
return anthropic.AsyncAnthropicFoundry(
|
|
30
|
+
resource=params.get("resource"), api_key=api_key_from_env(params),
|
|
31
|
+
base_url=params.get("base_url"), **common)
|
|
32
|
+
return anthropic.AsyncAnthropic(api_key=api_key_from_env(params), base_url=params.get("base_url"), **common)
|
|
33
|
+
except ProviderError:
|
|
34
|
+
raise
|
|
35
|
+
except Exception as exc: # missing region, project or credentials libraries
|
|
36
|
+
raise ProviderError("config_error", f"cannot set up the {platform} client: {exc}") from exc
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class AnthropicProvider:
|
|
40
|
+
"""Claude via the Messages API, first-party or on Amazon Bedrock, Google Cloud
|
|
41
|
+
Vertex AI or Microsoft Foundry. Structured output uses output_config.format.
|
|
42
|
+
|
|
43
|
+
Profile params, all platforms: max_tokens (default 16000), effort,
|
|
44
|
+
prompt_cache (default true: the system prompt, which holds the
|
|
45
|
+
instructions, schema and few-shot examples, carries a cache breakpoint),
|
|
46
|
+
extra_headers / extra_body (passed through, e.g. to enable refusal fallbacks).
|
|
47
|
+
anthropic: api_key_env, base_url
|
|
48
|
+
bedrock: aws_region, aws_profile, api_key_env (a Bedrock API key; else the AWS credential chain)
|
|
49
|
+
vertex: project_id, region (default global); Application Default Credentials
|
|
50
|
+
foundry: resource (or base_url), api_key_env
|
|
51
|
+
Provider batch mode (mod.attach mode => 'batch') uses the Message Batches API.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(self, model: str, params: dict, timeout: float, platform: str = "anthropic"):
|
|
55
|
+
self.name = platform
|
|
56
|
+
self.model = model
|
|
57
|
+
self.params = params
|
|
58
|
+
self.client = _client(platform, params, timeout)
|
|
59
|
+
|
|
60
|
+
def _system(self, system: str) -> Any:
|
|
61
|
+
if self.params.get("prompt_cache", True):
|
|
62
|
+
return [{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}]
|
|
63
|
+
return system
|
|
64
|
+
|
|
65
|
+
def _base_kwargs(self, system: str, messages: list) -> dict:
|
|
66
|
+
kwargs: dict = {
|
|
67
|
+
"model": self.model,
|
|
68
|
+
"max_tokens": int(self.params.get("max_tokens", 16000)),
|
|
69
|
+
"system": self._system(system),
|
|
70
|
+
"messages": messages,
|
|
71
|
+
}
|
|
72
|
+
if self.params.get("effort"):
|
|
73
|
+
kwargs["output_config"] = {"effort": self.params["effort"]}
|
|
74
|
+
if self.params.get("extra_headers"):
|
|
75
|
+
kwargs["extra_headers"] = self.params["extra_headers"]
|
|
76
|
+
if self.params.get("extra_body"):
|
|
77
|
+
kwargs["extra_body"] = self.params["extra_body"]
|
|
78
|
+
return kwargs
|
|
79
|
+
|
|
80
|
+
def _completion_kwargs(self, system: str, messages: list, schema: Optional[dict], strict: bool) -> dict:
|
|
81
|
+
kwargs = self._base_kwargs(system, messages)
|
|
82
|
+
if schema is not None and strict:
|
|
83
|
+
kwargs.setdefault("output_config", {})["format"] = {"type": "json_schema", "schema": schema}
|
|
84
|
+
return kwargs
|
|
85
|
+
|
|
86
|
+
async def _call(self, fn: Callable[..., Awaitable[Any]], **kwargs: Any) -> Any:
|
|
87
|
+
try:
|
|
88
|
+
return await fn(**kwargs)
|
|
89
|
+
except anthropic.APITimeoutError as exc:
|
|
90
|
+
raise ProviderError("timeout", str(exc), retryable=True) from exc
|
|
91
|
+
except anthropic.APIConnectionError as exc:
|
|
92
|
+
raise ProviderError("provider_unavailable", str(exc), retryable=True) from exc
|
|
93
|
+
except anthropic.RateLimitError as exc:
|
|
94
|
+
raise ProviderError("rate_limited", exc.message, retryable=True) from exc
|
|
95
|
+
except (anthropic.AuthenticationError, anthropic.PermissionDeniedError) as exc:
|
|
96
|
+
raise ProviderError("auth_error", exc.message) from exc
|
|
97
|
+
except anthropic.NotFoundError as exc:
|
|
98
|
+
raise ProviderError("config_error", f"model or endpoint not found: {exc.message}") from exc
|
|
99
|
+
except anthropic.BadRequestError as exc:
|
|
100
|
+
if "credit balance" in str(exc.message).lower():
|
|
101
|
+
raise ProviderError("quota_exceeded", f"the API account has no credit left: {exc.message}") from exc
|
|
102
|
+
raise ProviderError("bad_request", exc.message) from exc
|
|
103
|
+
except anthropic.APIStatusError as exc:
|
|
104
|
+
if exc.status_code >= 500 or exc.status_code in (408, 409):
|
|
105
|
+
raise ProviderError("provider_unavailable", exc.message, retryable=True) from exc
|
|
106
|
+
raise ProviderError("bad_request", exc.message) from exc
|
|
107
|
+
except anthropic.AnthropicError as exc:
|
|
108
|
+
raise ProviderError("bad_request", str(exc)) from exc
|
|
109
|
+
except ProviderError:
|
|
110
|
+
raise
|
|
111
|
+
except Exception as exc:
|
|
112
|
+
# Raised by platform auth before any request is sent, e.g. botocore's
|
|
113
|
+
# NoCredentialsError or google.auth's DefaultCredentialsError.
|
|
114
|
+
raise ProviderError("config_error", f"{self.name}: {type(exc).__name__}: {exc}") from exc
|
|
115
|
+
|
|
116
|
+
async def _create(self, kwargs: dict):
|
|
117
|
+
return await self._call(self.client.messages.create, **kwargs)
|
|
118
|
+
|
|
119
|
+
@staticmethod
|
|
120
|
+
def _completion(response: Any) -> Completion:
|
|
121
|
+
usage = response.usage
|
|
122
|
+
return Completion(
|
|
123
|
+
text="".join(block.text for block in response.content if block.type == "text"),
|
|
124
|
+
input_tokens=usage.input_tokens,
|
|
125
|
+
output_tokens=usage.output_tokens,
|
|
126
|
+
cache_read_tokens=getattr(usage, "cache_read_input_tokens", None),
|
|
127
|
+
cache_write_tokens=getattr(usage, "cache_creation_input_tokens", None),
|
|
128
|
+
reported_model=response.model,
|
|
129
|
+
request_id=getattr(response, "_request_id", None),
|
|
130
|
+
refused=response.stop_reason == "refusal",
|
|
131
|
+
truncated=response.stop_reason == "max_tokens",
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
async def complete(
|
|
135
|
+
self, *, system: str, messages: list[dict], schema: Optional[dict], strict: bool
|
|
136
|
+
) -> Completion:
|
|
137
|
+
response = await self._create(self._completion_kwargs(system, messages, schema, strict))
|
|
138
|
+
return self._completion(response)
|
|
139
|
+
|
|
140
|
+
async def chat(self, *, system: str, messages: list[dict], tools: list[dict]) -> Turn:
|
|
141
|
+
kwargs = self._base_kwargs(system, to_anthropic_messages(messages))
|
|
142
|
+
kwargs["tools"] = [
|
|
143
|
+
{"name": t["name"], "description": t["description"], "input_schema": t["input_schema"]} for t in tools
|
|
144
|
+
]
|
|
145
|
+
response = await self._create(kwargs)
|
|
146
|
+
return Turn(
|
|
147
|
+
text="".join(block.text for block in response.content if block.type == "text"),
|
|
148
|
+
tool_calls=[ToolCall(id=b.id, name=b.name, input=b.input if isinstance(b.input, dict) else {})
|
|
149
|
+
for b in response.content if b.type == "tool_use"],
|
|
150
|
+
# Every block, thinking included, goes back unchanged on the next request.
|
|
151
|
+
raw=[block.model_dump(mode="json", exclude_none=True) for block in response.content],
|
|
152
|
+
input_tokens=response.usage.input_tokens,
|
|
153
|
+
output_tokens=response.usage.output_tokens,
|
|
154
|
+
cache_read_tokens=getattr(response.usage, "cache_read_input_tokens", None),
|
|
155
|
+
cache_write_tokens=getattr(response.usage, "cache_creation_input_tokens", None),
|
|
156
|
+
refused=response.stop_reason == "refusal",
|
|
157
|
+
truncated=response.stop_reason == "max_tokens",
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
# ------------------------------------------------------------- batches
|
|
161
|
+
async def submit_batch(self, requests: list[dict]) -> str:
|
|
162
|
+
"""Message Batches API: about half price, results within 24 hours."""
|
|
163
|
+
batch_requests = []
|
|
164
|
+
for r in requests:
|
|
165
|
+
params = self._completion_kwargs(r["system"], r["messages"], r["schema"], r["strict"])
|
|
166
|
+
params.pop("extra_headers", None)
|
|
167
|
+
params.update(params.pop("extra_body", None) or {})
|
|
168
|
+
batch_requests.append({"custom_id": r["custom_id"], "params": params})
|
|
169
|
+
batch = await self._call(self.client.messages.batches.create, requests=batch_requests)
|
|
170
|
+
return batch.id
|
|
171
|
+
|
|
172
|
+
async def batch_status(self, batch_id: str) -> str:
|
|
173
|
+
batch = await self._call(self.client.messages.batches.retrieve, message_batch_id=batch_id)
|
|
174
|
+
return "ended" if batch.processing_status == "ended" else "in_progress"
|
|
175
|
+
|
|
176
|
+
async def batch_results(self, batch_id: str) -> dict:
|
|
177
|
+
async def fetch(**kwargs: Any) -> dict:
|
|
178
|
+
stream = self.client.messages.batches.results(**kwargs)
|
|
179
|
+
if inspect.isawaitable(stream):
|
|
180
|
+
stream = await stream
|
|
181
|
+
out: dict = {}
|
|
182
|
+
async for item in stream:
|
|
183
|
+
result = item.result
|
|
184
|
+
if result.type == "succeeded":
|
|
185
|
+
out[item.custom_id] = self._completion(result.message)
|
|
186
|
+
elif result.type == "errored":
|
|
187
|
+
error = getattr(result, "error", None)
|
|
188
|
+
inner = getattr(error, "error", error)
|
|
189
|
+
kind = getattr(inner, "type", "error")
|
|
190
|
+
message = getattr(inner, "message", str(error))
|
|
191
|
+
out[item.custom_id] = ProviderError(
|
|
192
|
+
"bad_request" if kind == "invalid_request_error" or kind == "invalid_request" else
|
|
193
|
+
"provider_unavailable", f"batch request errored: {kind}: {message}",
|
|
194
|
+
retryable=kind not in ("invalid_request_error", "invalid_request"))
|
|
195
|
+
else: # canceled or expired
|
|
196
|
+
out[item.custom_id] = ProviderError("provider_unavailable", f"batch request {result.type}",
|
|
197
|
+
retryable=True)
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
return await self._call(fetch, message_batch_id=batch_id)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def to_anthropic_messages(messages: list[dict]) -> list[dict]:
|
|
204
|
+
out: list[dict] = []
|
|
205
|
+
for m in messages:
|
|
206
|
+
if m["role"] == "user":
|
|
207
|
+
out.append({"role": "user", "content": m["content"]})
|
|
208
|
+
elif m["role"] == "assistant":
|
|
209
|
+
if m.get("provider") in CLAUDE_PLATFORMS and m.get("raw"):
|
|
210
|
+
content = m["raw"]
|
|
211
|
+
else: # produced by another provider: rebuild from the neutral form
|
|
212
|
+
content = ([{"type": "text", "text": m["text"]}] if m.get("text") else []) + [
|
|
213
|
+
{"type": "tool_use", "id": c["id"], "name": c["name"], "input": c["input"]}
|
|
214
|
+
for c in m.get("tool_calls", [])
|
|
215
|
+
]
|
|
216
|
+
out.append({"role": "assistant", "content": content or [{"type": "text", "text": "(no output)"}]})
|
|
217
|
+
elif m["role"] == "tool":
|
|
218
|
+
# All results of one turn go back in a single user message.
|
|
219
|
+
out.append({"role": "user", "content": [
|
|
220
|
+
{"type": "tool_result", "tool_use_id": r["id"], "content": r["content"], "is_error": r["is_error"]}
|
|
221
|
+
for r in m["results"]
|
|
222
|
+
]})
|
|
223
|
+
return out
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from typing import Any, Optional, Protocol
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class Completion:
|
|
8
|
+
text: str
|
|
9
|
+
input_tokens: Optional[int] = None
|
|
10
|
+
output_tokens: Optional[int] = None
|
|
11
|
+
reported_model: Optional[str] = None
|
|
12
|
+
request_id: Optional[str] = None
|
|
13
|
+
refused: bool = False
|
|
14
|
+
truncated: bool = False
|
|
15
|
+
cache_read_tokens: Optional[int] = None
|
|
16
|
+
cache_write_tokens: Optional[int] = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class ToolCall:
|
|
21
|
+
id: str
|
|
22
|
+
name: str
|
|
23
|
+
input: dict
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class Turn:
|
|
28
|
+
"""One assistant turn of a tool-using conversation (the agent).
|
|
29
|
+
|
|
30
|
+
`raw` is the provider's own representation of the turn, passed back
|
|
31
|
+
unchanged on later requests (Claude requires its thinking blocks back).
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
text: str
|
|
35
|
+
tool_calls: list[ToolCall] = field(default_factory=list)
|
|
36
|
+
raw: Any = None
|
|
37
|
+
input_tokens: Optional[int] = None
|
|
38
|
+
output_tokens: Optional[int] = None
|
|
39
|
+
refused: bool = False
|
|
40
|
+
truncated: bool = False
|
|
41
|
+
cache_read_tokens: Optional[int] = None
|
|
42
|
+
cache_write_tokens: Optional[int] = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# Conversations are kept provider-neutral, as a list of:
|
|
46
|
+
# {"role": "user", "content": str}
|
|
47
|
+
# {"role": "assistant", "text": str, "tool_calls": [{"id", "name", "input"}], "provider": str, "raw": ...}
|
|
48
|
+
# {"role": "tool", "results": [{"id", "name", "content": str, "is_error": bool}]}
|
|
49
|
+
# Tools are {"name", "description", "input_schema"}.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ProviderError(Exception):
|
|
53
|
+
"""A provider failure, normalised. `retryable` failures may succeed on retry."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, code: str, message: str, retryable: bool = False):
|
|
56
|
+
super().__init__(message)
|
|
57
|
+
self.code = code
|
|
58
|
+
self.retryable = retryable
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Provider(Protocol):
|
|
62
|
+
async def complete(
|
|
63
|
+
self,
|
|
64
|
+
*,
|
|
65
|
+
system: str,
|
|
66
|
+
messages: list[dict],
|
|
67
|
+
schema: Optional[dict],
|
|
68
|
+
strict: bool,
|
|
69
|
+
) -> Completion: ...
|
|
70
|
+
|
|
71
|
+
async def chat(self, *, system: str, messages: list[dict], tools: list[dict]) -> Turn: ...
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# Optional capabilities, checked with hasattr:
|
|
75
|
+
# async submit_batch(requests: [{custom_id, system, messages, schema, strict}]) -> batch id
|
|
76
|
+
# async batch_status(batch_id) -> "in_progress" | "ended"
|
|
77
|
+
# async batch_results(batch_id) -> {custom_id: Completion | ProviderError}
|
|
78
|
+
# async embed(texts: list[str]) -> list[list[float]]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def api_key_from_env(params: dict) -> Optional[str]:
|
|
82
|
+
"""The key named by params.api_key_env, or None to let the SDK use its default variable."""
|
|
83
|
+
var = params.get("api_key_env")
|
|
84
|
+
if not var:
|
|
85
|
+
return None
|
|
86
|
+
key = os.environ.get(var)
|
|
87
|
+
if not key:
|
|
88
|
+
raise ProviderError("config_error", f"environment variable {var} (params.api_key_env) is not set")
|
|
89
|
+
return key
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import re
|
|
6
|
+
import uuid
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
from ..schema import ENVELOPE_KEY, synthesize
|
|
10
|
+
from ..text import fold, trigrams
|
|
11
|
+
from .base import Completion, ProviderError, ToolCall, Turn
|
|
12
|
+
|
|
13
|
+
_UNMATCHED = object()
|
|
14
|
+
_PACKED_INPUT = re.compile(r'<input id="(\d+)">\n(.*?)\n</input>', re.DOTALL)
|
|
15
|
+
# Batches submitted to fake providers, shared across instances (a worker restart keeps them).
|
|
16
|
+
BATCHES: dict[str, dict] = {}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class FakeProvider:
|
|
20
|
+
"""Deterministic provider for tests and demos without credentials.
|
|
21
|
+
|
|
22
|
+
Profile params:
|
|
23
|
+
responses: {"substring": value}. The longest key found in the input wins.
|
|
24
|
+
text: reply for free-text calls (default "ok").
|
|
25
|
+
fail: error code to raise on every call (retryable if it is rate_limited/timeout).
|
|
26
|
+
fail_times: raise `fail` only for this many calls, then succeed.
|
|
27
|
+
raw: return this string verbatim (to exercise invalid-output handling).
|
|
28
|
+
delay: seconds to wait before answering.
|
|
29
|
+
pack_drop: in a packed call, leave out the answers of inputs containing these substrings.
|
|
30
|
+
cache_read: report this many cache-read input tokens per call.
|
|
31
|
+
batch_polls: how many status checks a submitted batch stays in progress (default 0).
|
|
32
|
+
Otherwise it returns a minimal value that satisfies the schema.
|
|
33
|
+
|
|
34
|
+
For the agent (chat), params.script is a list of turns played in order,
|
|
35
|
+
each {"text": ..., "tool_calls": [{"name": ..., "input": {...}}]}; after the
|
|
36
|
+
script it answers params.final (default "Done."). Each turn reports 100
|
|
37
|
+
input and 20 output tokens.
|
|
38
|
+
|
|
39
|
+
embed() returns deterministic 64-dimension vectors of character trigrams,
|
|
40
|
+
so similar strings get similar vectors.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
name = "fake"
|
|
44
|
+
|
|
45
|
+
def __init__(self, model: str, params: dict, timeout: float):
|
|
46
|
+
self.params = params
|
|
47
|
+
self.calls = 0
|
|
48
|
+
|
|
49
|
+
async def _maybe_fail(self) -> None:
|
|
50
|
+
self.calls += 1
|
|
51
|
+
if self.params.get("delay"):
|
|
52
|
+
await asyncio.sleep(self.params["delay"])
|
|
53
|
+
fail = self.params.get("fail")
|
|
54
|
+
if fail and self.calls <= self.params.get("fail_times", float("inf")):
|
|
55
|
+
raise ProviderError(fail, f"fake failure: {fail}", retryable=fail in ("rate_limited", "timeout"))
|
|
56
|
+
|
|
57
|
+
async def chat(self, *, system: str, messages: list[dict], tools: list[dict]) -> Turn:
|
|
58
|
+
await self._maybe_fail()
|
|
59
|
+
self.last_messages = messages
|
|
60
|
+
turn_index = sum(1 for m in messages if m["role"] == "assistant")
|
|
61
|
+
script = self.params.get("script", [])
|
|
62
|
+
if turn_index >= len(script):
|
|
63
|
+
return Turn(text=self.params.get("final", "Done."), input_tokens=100, output_tokens=20)
|
|
64
|
+
step = script[turn_index]
|
|
65
|
+
calls = [ToolCall(id=f"call_{turn_index}_{i}", name=c["name"], input=c.get("input", {}))
|
|
66
|
+
for i, c in enumerate(step.get("tool_calls", []))]
|
|
67
|
+
return Turn(text=step.get("text", ""), tool_calls=calls, raw={"turn": turn_index},
|
|
68
|
+
input_tokens=100, output_tokens=20)
|
|
69
|
+
|
|
70
|
+
def _answer(self, text: str, value_schema: Optional[dict]):
|
|
71
|
+
# The longest matching key wins (profile params are jsonb, which does not keep key order).
|
|
72
|
+
for needle, answer in sorted(self.params.get("responses", {}).items(), key=lambda kv: -len(kv[0])):
|
|
73
|
+
if needle in text:
|
|
74
|
+
return answer
|
|
75
|
+
if value_schema is None:
|
|
76
|
+
return _UNMATCHED
|
|
77
|
+
return synthesize(value_schema)
|
|
78
|
+
|
|
79
|
+
def _respond(self, system: str, user: str, schema: Optional[dict]) -> Completion:
|
|
80
|
+
tokens = {"input_tokens": len(system + user) // 4, "output_tokens": 1,
|
|
81
|
+
"cache_read_tokens": self.params.get("cache_read")}
|
|
82
|
+
if "raw" in self.params:
|
|
83
|
+
return Completion(text=self.params["raw"], **tokens)
|
|
84
|
+
if schema is not None and "items" in schema.get("properties", {}):
|
|
85
|
+
item_schema = schema["properties"]["items"]["items"]["properties"][ENVELOPE_KEY]
|
|
86
|
+
items = []
|
|
87
|
+
for number, text in _PACKED_INPUT.findall(user):
|
|
88
|
+
if any(needle in text for needle in self.params.get("pack_drop", [])):
|
|
89
|
+
continue
|
|
90
|
+
items.append({"id": int(number), ENVELOPE_KEY: self._answer(text, item_schema)})
|
|
91
|
+
tokens["output_tokens"] = max(1, len(items))
|
|
92
|
+
return Completion(text=json.dumps({"items": items}), **tokens)
|
|
93
|
+
if schema is None:
|
|
94
|
+
value = self._answer(user, None)
|
|
95
|
+
return Completion(text=self.params.get("text", "ok") if value is _UNMATCHED else value, **tokens)
|
|
96
|
+
value = self._answer(user, schema["properties"][ENVELOPE_KEY])
|
|
97
|
+
return Completion(text=json.dumps({ENVELOPE_KEY: value}), **tokens)
|
|
98
|
+
|
|
99
|
+
async def complete(
|
|
100
|
+
self, *, system: str, messages: list[dict], schema: Optional[dict], strict: bool
|
|
101
|
+
) -> Completion:
|
|
102
|
+
await self._maybe_fail()
|
|
103
|
+
self.last_system = system
|
|
104
|
+
return self._respond(system, messages[0]["content"], schema) # later turns are repair prompts
|
|
105
|
+
|
|
106
|
+
async def embed(self, texts: list[str]) -> list[list[float]]:
|
|
107
|
+
await self._maybe_fail()
|
|
108
|
+
vectors = []
|
|
109
|
+
for text in texts:
|
|
110
|
+
vector = [0.0] * 64
|
|
111
|
+
for gram in trigrams(fold(text)):
|
|
112
|
+
vector[int(hashlib.md5(gram.encode("utf-8")).hexdigest(), 16) % 64] += 1.0
|
|
113
|
+
norm = math.sqrt(sum(v * v for v in vector)) or 1.0
|
|
114
|
+
vectors.append([v / norm for v in vector])
|
|
115
|
+
return vectors
|
|
116
|
+
|
|
117
|
+
# ------------------------------------------------------------- batches
|
|
118
|
+
async def submit_batch(self, requests: list[dict]) -> str:
|
|
119
|
+
await self._maybe_fail()
|
|
120
|
+
batch_id = f"fakebatch_{uuid.uuid4().hex[:12]}"
|
|
121
|
+
results = {}
|
|
122
|
+
for r in requests:
|
|
123
|
+
if any(needle in r["messages"][0]["content"] for needle in self.params.get("batch_errors", [])):
|
|
124
|
+
results[r["custom_id"]] = ProviderError("provider_unavailable", "fake batch item error", retryable=True)
|
|
125
|
+
else:
|
|
126
|
+
results[r["custom_id"]] = self._respond(r["system"], r["messages"][0]["content"], r["schema"])
|
|
127
|
+
BATCHES[batch_id] = {"polls_left": int(self.params.get("batch_polls", 0)), "results": results}
|
|
128
|
+
return batch_id
|
|
129
|
+
|
|
130
|
+
async def batch_status(self, batch_id: str) -> str:
|
|
131
|
+
batch = BATCHES.get(batch_id)
|
|
132
|
+
if batch is None:
|
|
133
|
+
raise ProviderError("config_error", f"unknown batch {batch_id}")
|
|
134
|
+
if batch["polls_left"] > 0:
|
|
135
|
+
batch["polls_left"] -= 1
|
|
136
|
+
return "in_progress"
|
|
137
|
+
return "ended"
|
|
138
|
+
|
|
139
|
+
async def batch_results(self, batch_id: str) -> dict:
|
|
140
|
+
return dict(BATCHES[batch_id]["results"])
|