metergraph-core 0.8.22__tar.gz → 0.8.25__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {metergraph_core-0.8.22/src/metergraph_core.egg-info → metergraph_core-0.8.25}/PKG-INFO +108 -1
  2. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/README.md +107 -0
  3. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/pyproject.toml +1 -1
  4. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/__init__.py +8 -2
  5. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/calls.py +114 -5
  6. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/catalog.py +1 -0
  7. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/data/models.yaml +50 -0
  8. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/data/prices.yaml +26 -2
  9. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/models.py +241 -1
  10. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/retrieval.py +1 -1
  11. {metergraph_core-0.8.22 → metergraph_core-0.8.25/src/metergraph_core.egg-info}/PKG-INFO +108 -1
  12. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/MANIFEST.in +0 -0
  13. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/setup.cfg +0 -0
  14. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/billing.py +0 -0
  15. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/catalog_delta.py +0 -0
  16. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/data/sources.yaml +0 -0
  17. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/extractors.py +0 -0
  18. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/families.py +0 -0
  19. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/loader.py +0 -0
  20. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/refresh.py +0 -0
  21. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/reliability.py +0 -0
  22. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/responses.py +0 -0
  23. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core/sources.py +0 -0
  24. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core.egg-info/SOURCES.txt +0 -0
  25. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core.egg-info/dependency_links.txt +0 -0
  26. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core.egg-info/requires.txt +0 -0
  27. {metergraph_core-0.8.22 → metergraph_core-0.8.25}/src/metergraph_core.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: metergraph-core
3
- Version: 0.8.22
3
+ Version: 0.8.25
4
4
  Summary: Open, effective-dated LLM pricing catalog and deterministic cost calculator for popular models across major providers and gateways, including OpenAI, Anthropic, Google Gemini, AWS Bedrock, OpenRouter, Vercel AI Gateway, and more.
5
5
  Author: Metergraph
6
6
  License-Expression: Apache-2.0
@@ -312,6 +312,35 @@ such as `priority` or `flex`, returns `partial` with `service_tier` in
312
312
  call from its final response or final usage chunk. Fees outside token usage,
313
313
  such as web search, are not included.
314
314
 
315
+ ### Complete costs from captured usage
316
+
317
+ `price_call_from_record()` accepts normalized SDK or relay usage, without reading
318
+ prompt or response content:
319
+
320
+ ```python
321
+ from metergraph_core import price_call_from_record
322
+
323
+ result = price_call_from_record({
324
+ "provider": "perplexity", "model": "perplexity/sonar",
325
+ "retrieval_api": "agent", "search_type": "web", "web_search_calls": 3,
326
+ "input_tokens": 1000, "output_tokens": 100, "ts": "2026-11-18T12:00:00Z",
327
+ })
328
+ print(result.status, result.cost_usd, result.retrieval_cost_usd)
329
+ ```
330
+
331
+ Core selects the API channel, retrieval operation, and billing unit. Supported
332
+ record evidence includes OpenAI search counts, Anthropic server-tool usage,
333
+ Google grounding queries, and Perplexity Agent standard/fast invocation counts.
334
+ Older Gemini grounded prompts do not inherit newer per-query rates. An unknown
335
+ rate, count, search type, or processing tier stays partial or unpriced.
336
+ `search_units` and `retrieval_cost_usd` expose the resolved components for storage.
337
+ `known_subtotal_usd` remains separate from a complete total.
338
+
339
+ A receiver that already resolved tokens against the same catalog may pass
340
+ `token_cost=`. Explicit API identity can select a different token channel; other
341
+ resolved token results are preserved. Qualified gateway totals can still be
342
+ reconciled separately with `resolve_billing()`.
343
+
315
344
  ## Model registry
316
345
 
317
346
  ```python
@@ -348,6 +377,84 @@ mismatches on any route, mismatched offer-group credentials/providers, and dupli
348
377
  remains exclusively in `prices.yaml`; being priceable does not automatically
349
378
  make a model an approved analysis candidate.
350
379
 
380
+ ### Training policy
381
+
382
+ `models.effective_training_policy(route_key)` says whether the route's
383
+ serving provider may train on customer inputs and outputs under its default
384
+ terms. It returns an `EffectiveTrainingPolicy` holding the `TrainingPolicy`,
385
+ the level it came from (`origin`) and the registry `version` that recorded
386
+ it. An unknown route key raises `KeyError`.
387
+
388
+ ```python
389
+ effective = models.effective_training_policy("default:openai/gpt-5.6-sol")
390
+ print(effective.policy.training_on_customer_data, effective.origin)
391
+ ```
392
+
393
+ `training_on_customer_data` is one of:
394
+
395
+ - `prohibited`: the default applicable terms exclude training on customer
396
+ inputs and outputs.
397
+ - `conditional`: training is excluded only when `conditions` hold, such as a
398
+ paid tier or an opt-out.
399
+ - `permitted`: the terms allow training.
400
+ - `unknown`: no explicit promise was found. A missing promise is `unknown`,
401
+ not `permitted`.
402
+
403
+ Every value except `unknown` cites an HTTPS `source`. Only `conditional` has
404
+ `conditions`. No value verifies an account’s configuration, opt-ins, or
405
+ separate agreements. The registry version and Git history record when a
406
+ policy changed.
407
+
408
+ The document records policies at three levels, keyed by the route's serving
409
+ `provider` and `pricing_channel`:
410
+
411
+ ```yaml
412
+ provider_defaults:
413
+ openai:
414
+ openai-api:
415
+ training_policy:
416
+ training_on_customer_data: prohibited
417
+ source: https://example.com/terms
418
+ models:
419
+ - canonical_id: example/model
420
+ training_policy_overrides: # this model on one provider and channel
421
+ vercel:
422
+ vercel-ai-gateway:
423
+ training_policy: {training_on_customer_data: unknown}
424
+ routes:
425
+ - key: default:example/model
426
+ training_policy: # this route only
427
+ training_on_customer_data: unknown
428
+ ```
429
+
430
+ The route's own `training_policy` wins. Otherwise the model's override for
431
+ the route's provider and channel applies, then that pair's provider default,
432
+ then `unknown` with origin `unspecified`. The first policy found replaces the
433
+ others whole, so an explicit `unknown` stops inheritance. The publisher is
434
+ never used. A gateway or cloud host such as `vercel` or `bedrock` follows its
435
+ own terms, not those of the model's publisher. The parser rejects unknown
436
+ policy fields, a provider/channel pair that no route could use, and a model
437
+ override for a pair the model has no route on. Documents without policies
438
+ still load, and every route resolves to `unknown`.
439
+
440
+ The bundled registry records a default for every serving provider. The YAML
441
+ is the source of truth for current policy values, sources and conditions:
442
+
443
+ ```python
444
+ for provider, channels in models.training_policy_defaults.items():
445
+ for channel, policy in channels.items():
446
+ print(provider, channel, policy.training_on_customer_data, policy.source)
447
+ ```
448
+
449
+ Adding a model normally requires no policy entry: it inherits the serving
450
+ provider's default. Add a model or route override only when its terms differ.
451
+ To update a provider policy, edit that one YAML object and increment the
452
+ existing registry version; source URLs and values are not duplicated in tests
453
+ or a documentation table. Changes still require review against the linked
454
+ official terms. There is no network lookup, scheduled refresher, extra
455
+ dependency or per-policy date to maintain. Policy lookup is explicit and does
456
+ not run during pricing or candidate selection.
457
+
351
458
  ## Billing evidence
352
459
 
353
460
  Servers can pass content-blind, already-extracted gateway fields through the
@@ -282,6 +282,35 @@ such as `priority` or `flex`, returns `partial` with `service_tier` in
282
282
  call from its final response or final usage chunk. Fees outside token usage,
283
283
  such as web search, are not included.
284
284
 
285
+ ### Complete costs from captured usage
286
+
287
+ `price_call_from_record()` accepts normalized SDK or relay usage, without reading
288
+ prompt or response content:
289
+
290
+ ```python
291
+ from metergraph_core import price_call_from_record
292
+
293
+ result = price_call_from_record({
294
+ "provider": "perplexity", "model": "perplexity/sonar",
295
+ "retrieval_api": "agent", "search_type": "web", "web_search_calls": 3,
296
+ "input_tokens": 1000, "output_tokens": 100, "ts": "2026-11-18T12:00:00Z",
297
+ })
298
+ print(result.status, result.cost_usd, result.retrieval_cost_usd)
299
+ ```
300
+
301
+ Core selects the API channel, retrieval operation, and billing unit. Supported
302
+ record evidence includes OpenAI search counts, Anthropic server-tool usage,
303
+ Google grounding queries, and Perplexity Agent standard/fast invocation counts.
304
+ Older Gemini grounded prompts do not inherit newer per-query rates. An unknown
305
+ rate, count, search type, or processing tier stays partial or unpriced.
306
+ `search_units` and `retrieval_cost_usd` expose the resolved components for storage.
307
+ `known_subtotal_usd` remains separate from a complete total.
308
+
309
+ A receiver that already resolved tokens against the same catalog may pass
310
+ `token_cost=`. Explicit API identity can select a different token channel; other
311
+ resolved token results are preserved. Qualified gateway totals can still be
312
+ reconciled separately with `resolve_billing()`.
313
+
285
314
  ## Model registry
286
315
 
287
316
  ```python
@@ -318,6 +347,84 @@ mismatches on any route, mismatched offer-group credentials/providers, and dupli
318
347
  remains exclusively in `prices.yaml`; being priceable does not automatically
319
348
  make a model an approved analysis candidate.
320
349
 
350
+ ### Training policy
351
+
352
+ `models.effective_training_policy(route_key)` says whether the route's
353
+ serving provider may train on customer inputs and outputs under its default
354
+ terms. It returns an `EffectiveTrainingPolicy` holding the `TrainingPolicy`,
355
+ the level it came from (`origin`) and the registry `version` that recorded
356
+ it. An unknown route key raises `KeyError`.
357
+
358
+ ```python
359
+ effective = models.effective_training_policy("default:openai/gpt-5.6-sol")
360
+ print(effective.policy.training_on_customer_data, effective.origin)
361
+ ```
362
+
363
+ `training_on_customer_data` is one of:
364
+
365
+ - `prohibited`: the default applicable terms exclude training on customer
366
+ inputs and outputs.
367
+ - `conditional`: training is excluded only when `conditions` hold, such as a
368
+ paid tier or an opt-out.
369
+ - `permitted`: the terms allow training.
370
+ - `unknown`: no explicit promise was found. A missing promise is `unknown`,
371
+ not `permitted`.
372
+
373
+ Every value except `unknown` cites an HTTPS `source`. Only `conditional` has
374
+ `conditions`. No value verifies an account’s configuration, opt-ins, or
375
+ separate agreements. The registry version and Git history record when a
376
+ policy changed.
377
+
378
+ The document records policies at three levels, keyed by the route's serving
379
+ `provider` and `pricing_channel`:
380
+
381
+ ```yaml
382
+ provider_defaults:
383
+ openai:
384
+ openai-api:
385
+ training_policy:
386
+ training_on_customer_data: prohibited
387
+ source: https://example.com/terms
388
+ models:
389
+ - canonical_id: example/model
390
+ training_policy_overrides: # this model on one provider and channel
391
+ vercel:
392
+ vercel-ai-gateway:
393
+ training_policy: {training_on_customer_data: unknown}
394
+ routes:
395
+ - key: default:example/model
396
+ training_policy: # this route only
397
+ training_on_customer_data: unknown
398
+ ```
399
+
400
+ The route's own `training_policy` wins. Otherwise the model's override for
401
+ the route's provider and channel applies, then that pair's provider default,
402
+ then `unknown` with origin `unspecified`. The first policy found replaces the
403
+ others whole, so an explicit `unknown` stops inheritance. The publisher is
404
+ never used. A gateway or cloud host such as `vercel` or `bedrock` follows its
405
+ own terms, not those of the model's publisher. The parser rejects unknown
406
+ policy fields, a provider/channel pair that no route could use, and a model
407
+ override for a pair the model has no route on. Documents without policies
408
+ still load, and every route resolves to `unknown`.
409
+
410
+ The bundled registry records a default for every serving provider. The YAML
411
+ is the source of truth for current policy values, sources and conditions:
412
+
413
+ ```python
414
+ for provider, channels in models.training_policy_defaults.items():
415
+ for channel, policy in channels.items():
416
+ print(provider, channel, policy.training_on_customer_data, policy.source)
417
+ ```
418
+
419
+ Adding a model normally requires no policy entry: it inherits the serving
420
+ provider's default. Add a model or route override only when its terms differ.
421
+ To update a provider policy, edit that one YAML object and increment the
422
+ existing registry version; source URLs and values are not duplicated in tests
423
+ or a documentation table. Changes still require review against the linked
424
+ official terms. There is no network lookup, scheduled refresher, extra
425
+ dependency or per-policy date to maintain. Policy lookup is explicit and does
426
+ not run during pricing or candidate selection.
427
+
321
428
  ## Billing evidence
322
429
 
323
430
  Servers can pass content-blind, already-extracted gateway fields through the
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "metergraph-core"
3
- version = "0.8.22"
3
+ version = "0.8.25"
4
4
  description = "Open, effective-dated LLM pricing catalog and deterministic cost calculator for popular models across major providers and gateways, including OpenAI, Anthropic, Google Gemini, AWS Bedrock, OpenRouter, Vercel AI Gateway, and more."
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -32,12 +32,15 @@ from .loader import (
32
32
  parse_retrieval,
33
33
  )
34
34
  from .models import (
35
+ TRAINING_ON_CUSTOMER_DATA,
36
+ EffectiveTrainingPolicy,
35
37
  ModelDefinition,
36
38
  ModelRegistry,
37
39
  ModelRegistryError,
38
40
  ModelRoute,
39
41
  OfferGroup,
40
42
  ReleaseDate,
43
+ TrainingPolicy,
41
44
  load_model_registry,
42
45
  parse_model_registry,
43
46
  validate_model_registry,
@@ -128,6 +131,9 @@ __all__ = [
128
131
  "ModelUsage",
129
132
  "OfferGroup",
130
133
  "ReleaseDate",
134
+ "EffectiveTrainingPolicy",
135
+ "TRAINING_ON_CUSTOMER_DATA",
136
+ "TrainingPolicy",
131
137
  "GatewayBillingEvidence",
132
138
  "Price",
133
139
  "PriceResult",
@@ -159,10 +165,10 @@ __all__ = [
159
165
  ]
160
166
 
161
167
  from .calls import (CallCostResult, RetrievalComponent, RetrievalUsage, compose_call_cost,
162
- price_call, price_call_from_response, response_retrieval_usage)
168
+ price_call, price_call_from_record, price_call_from_response, response_retrieval_usage)
163
169
 
164
170
  __all__ += ["CallCostResult", "RetrievalComponent", "RetrievalUsage", "compose_call_cost",
165
- "price_call", "price_call_from_response", "response_retrieval_usage"]
171
+ "price_call", "price_call_from_record", "price_call_from_response", "response_retrieval_usage"]
166
172
 
167
173
  from .reliability import ModelReliability, classify_model_reliability, classify_recorded_call
168
174
 
@@ -1,13 +1,14 @@
1
1
  """Compose token and counted retrieval costs from one catalog snapshot."""
2
2
  from __future__ import annotations
3
3
 
4
- from dataclasses import dataclass
4
+ from dataclasses import dataclass, replace
5
5
  from decimal import Decimal
6
+ import re
6
7
  from typing import Any, Mapping, Sequence
7
8
 
8
9
  from .catalog import CostResult, ModelUsage, direct_channel_for_provider, normalize_provider
9
10
  from .loader import LoadedCatalog
10
- from .responses import _as_mapping, _bundled_catalog, _first, cost_from_response, response_format
11
+ from .responses import _as_mapping, _bundled_catalog, _first, cost_from_response, response_format, _native_input_tokens
11
12
 
12
13
  _ZERO = Decimal('0')
13
14
 
@@ -56,6 +57,42 @@ class CallCostResult:
56
57
  *(f"missing_{d}" for d in self.missing_dimensions))))
57
58
 
58
59
 
60
+ @property
61
+ def retrieval_cost_usd(self) -> Decimal | None:
62
+ if not self.retrieval or any(item.cost_usd is None for item in self.retrieval):
63
+ return None
64
+ return sum((item.cost_usd for item in self.retrieval), _ZERO)
65
+
66
+ @property
67
+ def search_units(self) -> int | None:
68
+ searches = [item for item in self.retrieval if item.operation.startswith(
69
+ ('web_search', 'google_search', 'search_request'))]
70
+ if not searches or any(type(item.units) is not int or item.units < 0 for item in searches):
71
+ return None
72
+ return sum(item.units for item in searches)
73
+
74
+
75
+ def _grounding_operation(model: str | None) -> str:
76
+ match = re.search(r'(?:^|/)gemini-(\d+)', model or '')
77
+ if match is None:
78
+ return 'google_search_unknown'
79
+ return 'google_search_grounding' if int(match[1]) >= 3 else 'google_search_grounded_prompt'
80
+
81
+
82
+ def _supported_retrieval(channel, publisher, model, operation):
83
+ if channel == 'perplexity-agent-api':
84
+ return operation in {'web_search', 'web_search_fast'}
85
+ if channel == 'perplexity-api':
86
+ return operation in {'search_request_low', 'search_request_medium', 'search_request_high'}
87
+ if channel == 'openai-api' and publisher == 'openai':
88
+ return operation == 'web_search'
89
+ if channel == 'anthropic-api' and publisher == 'anthropic':
90
+ return operation in {'web_search', 'web_fetch'}
91
+ if channel in {'google-api', 'google-vertex-ai'} and publisher == 'google':
92
+ return operation == _grounding_operation(model)
93
+ return False
94
+
95
+
59
96
  def compose_call_cost(
60
97
  token_cost: CostResult, *, catalog: LoadedCatalog,
61
98
  retrieval: Sequence[RetrievalUsage] = (), provider: str | None = None,
@@ -88,11 +125,14 @@ def compose_call_cost(
88
125
  token_basis = 'unknown'
89
126
  parts = []
90
127
  for usage in retrieval:
91
- if resolved_channel == 'anthropic-api' and publisher == 'anthropic' and usage.operation in {'web_search', 'web_fetch'}:
128
+ if _supported_retrieval(resolved_channel, publisher, token_cost.canonical_model, usage.operation):
92
129
  fee = catalog.price_retrieval(channel=resolved_channel, operation=usage.operation,
93
130
  units=usage.units, at=token_cost.effective_at, region=region)
94
- part = RetrievalComponent(usage.operation, usage.units, fee.cost_usd,
95
- fee.price_id, 'exact' if fee.status == 'priced' else 'unknown', fee.reasons, fee.source_url)
131
+ # A measured zero incurs no fee even when its current rate is unknown.
132
+ zero = type(usage.units) is int and usage.units == 0
133
+ part = RetrievalComponent(usage.operation, usage.units, _ZERO if zero else fee.cost_usd,
134
+ fee.price_id, 'exact' if zero or fee.status == 'priced' else 'unknown',
135
+ () if zero else fee.reasons, fee.source_url)
96
136
  else:
97
137
  part = RetrievalComponent(usage.operation, usage.units, None, None,
98
138
  'unknown', ('unsupported_retrieval_scope',))
@@ -186,3 +226,72 @@ def price_call_from_response(
186
226
  return compose_call_cost(tokens, catalog=loaded,
187
227
  retrieval=response_retrieval_usage(response, format=format), provider=provider,
188
228
  channel=channel or direct_channel_for_provider(provider), region=region or 'global')
229
+
230
+
231
+ def _record_retrieval_usage(row: Mapping[str, Any], model: str | None) -> tuple[RetrievalUsage, ...]:
232
+ provider = normalize_provider(row.get('provider') or '')
233
+ if provider in {'perplexity-ai', 'perplexity-agent'}:
234
+ if row.get('retrieval_api') == 'agent' or provider == 'perplexity-agent':
235
+ units = row.get('web_search_calls')
236
+ operation = {'web': 'web_search', 'fast': 'web_search_fast'}.get(row.get('search_type'))
237
+ if type(units) is int and units == 0:
238
+ operation = 'web_search'
239
+ return (RetrievalUsage(operation or 'web_search_unknown', units),)
240
+ context = row.get('search_context_size', 'low')
241
+ operation = f'search_request_{context}' if context in {'low', 'medium', 'high'} else 'search_request_unknown'
242
+ return (RetrievalUsage(operation, 1),)
243
+ if provider in {'google', 'vertex-ai'} and 'grounding_queries' in row:
244
+ operation = _grounding_operation(model)
245
+ units = row['grounding_queries']
246
+ if operation == 'google_search_grounded_prompt':
247
+ units = row.get('grounded_prompt')
248
+ if units is None and type(row['grounding_queries']) is int and row['grounding_queries'] >= 0:
249
+ units = int(row['grounding_queries'] > 0)
250
+ return (RetrievalUsage(operation, units),)
251
+ found = {}
252
+ if 'server_tool_use' in row:
253
+ found = {item.operation: item for item in response_retrieval_usage(
254
+ {'usage': {'server_tool_use': row['server_tool_use']}}, format='anthropic.messages')}
255
+ if 'web_search_calls' in row and (row['web_search_calls'] is not None or 'web_search' not in found):
256
+ found['web_search'] = RetrievalUsage('web_search', row['web_search_calls'])
257
+ tools = row.get('tool_calls')
258
+ if isinstance(tools, list):
259
+ for kind, operation in (('web_search_call', 'web_search'), ('web_fetch_call', 'web_fetch')):
260
+ units = sum(isinstance(tool, Mapping) and tool.get('type') == kind for tool in tools)
261
+ if units and operation not in found:
262
+ found[operation] = RetrievalUsage(operation, units)
263
+ return tuple(found.values())
264
+
265
+
266
+ def price_call_from_record(
267
+ row: Mapping[str, Any], *, catalog: LoadedCatalog | None = None,
268
+ token_cost: CostResult | None = None, at: Any = None, region: str = 'global',
269
+ ) -> CallCostResult:
270
+ """Price normalized SDK/relay usage; provider billing policy stays here.
271
+
272
+ A receiver may supply its resolved token result from the same catalog.
273
+ Explicit API identity takes precedence when it selects a different channel.
274
+ No prompt or response content is read.
275
+ """
276
+ loaded = catalog if catalog is not None else _bundled_catalog()
277
+ provider = row.get('provider')
278
+ when = at if at is not None else token_cost.effective_at if token_cost is not None and token_cost.effective_at is not None else row.get('ts')
279
+ agent = normalize_provider(provider or '') in {'perplexity-ai', 'perplexity-agent'} and (
280
+ row.get('retrieval_api') == 'agent' or provider == 'perplexity-agent')
281
+ channel = 'perplexity-agent-api' if agent else direct_channel_for_provider(provider)
282
+ if token_cost is None or token_cost.effective_at is None or agent:
283
+ values = {key: row.get(key) for key in ('input_tokens', 'output_tokens', 'cache_read_tokens',
284
+ 'cache_write_tokens', 'cache_write_5m_tokens', 'cache_write_1h_tokens')}
285
+ def cost(**usage):
286
+ return loaded.calculate_cost(model=row.get('model'), usage=ModelUsage(**usage, batch=row.get('batch') is True),
287
+ at=when, provider=provider, channel=channel, region=region)
288
+ if row.get('input_tokens_include_cache') is True:
289
+ values['input_tokens'] = _native_input_tokens(values, cost)
290
+ token_cost = cost(**values)
291
+ tier = row.get('service_tier')
292
+ if tier is not None and tier not in ('standard', 'default', 'auto', 'batch'):
293
+ token_cost = replace(token_cost, status='partial',
294
+ missing_dimensions=tuple(dict.fromkeys((*token_cost.missing_dimensions, 'service_tier'))))
295
+ model = token_cost.canonical_model or row.get('model')
296
+ return compose_call_cost(token_cost, catalog=loaded, provider=provider, channel=channel,
297
+ region=region, retrieval=_record_retrieval_usage(row, model))
@@ -45,6 +45,7 @@ _DIRECT_CHANNEL_BY_PROVIDER = {
45
45
  "bedrock": "aws-bedrock",
46
46
  "deepseek": "deepseek-api",
47
47
  "perplexity-ai": "perplexity-api",
48
+ "perplexity-agent": "perplexity-agent-api",
48
49
  "x-ai": "xai-api",
49
50
  "alibaba": "alibaba-api",
50
51
  # Amazon publishes no first-party inference API: its own models are sold
@@ -1,4 +1,54 @@
1
1
  version: '2026-11-17'
2
+ # Training use of customer inputs and outputs under each serving provider's
3
+ # default terms. A pair left out resolves to unknown. A gateway or cloud host
4
+ # follows its own terms, never the model publisher's. No policy verifies an
5
+ # account's configuration, opt-ins or separate agreements.
6
+ provider_defaults:
7
+ anthropic:
8
+ anthropic-api:
9
+ training_policy:
10
+ training_on_customer_data: prohibited
11
+ source: https://www.anthropic.com/legal/commercial-terms
12
+ bedrock:
13
+ aws-bedrock:
14
+ training_policy:
15
+ training_on_customer_data: prohibited
16
+ source: https://aws.amazon.com/bedrock/faqs/
17
+ fireworks:
18
+ fireworks-api:
19
+ training_policy:
20
+ training_on_customer_data: prohibited
21
+ source: https://fireworks.ai/privacy-policy
22
+ mistral:
23
+ mistral-api:
24
+ training_policy:
25
+ training_on_customer_data: conditional
26
+ source: https://legal.mistral.ai/terms/commercial-terms-of-service/
27
+ conditions: >-
28
+ Requires the API training opt-out set by an organization admin
29
+ (https://help.mistral.ai/en/articles/455207-can-i-opt-out-of-my-input-or-output-data-being-used-for-training),
30
+ a model that is not a Labs or Preview model, no content submitted as
31
+ feedback, and no contrary order form.
32
+ moonshotai:
33
+ moonshot-api:
34
+ training_policy:
35
+ training_on_customer_data: permitted
36
+ source: https://platform.kimi.ai/docs/agreement/modeluse
37
+ openai:
38
+ openai-api:
39
+ training_policy:
40
+ training_on_customer_data: prohibited
41
+ source: https://developers.openai.com/api/docs/guides/your-data
42
+ tinker:
43
+ tinker-serverless:
44
+ training_policy:
45
+ training_on_customer_data: prohibited
46
+ source: https://thinkingmachines.ai/legal/terms/
47
+ vercel:
48
+ vercel-ai-gateway:
49
+ training_policy:
50
+ training_on_customer_data: unknown
51
+ source: https://vercel.com/docs/ai-gateway/security-and-compliance/disallow-prompt-training
2
52
  models:
3
53
  - canonical_id: openai/gpt-5.6-sol
4
54
  display_name: GPT-5.6 Sol
@@ -6,9 +6,9 @@
6
6
  #
7
7
  # Community updates welcome: add an alias or price entry with its provider
8
8
  # source_url and open a PR. CI validates structure and date overlaps.
9
- version: "2026-11-17"
9
+ version: "2026-11-18"
10
10
  currency: USD
11
- pricing_verified_at: "2026-11-17"
11
+ pricing_verified_at: "2026-11-18"
12
12
  models:
13
13
  - canonical_id: openai/gpt-6-sol
14
14
  publisher: openai
@@ -3210,7 +3210,16 @@ models:
3210
3210
  rules:
3211
3211
  input_includes_cache_read: true
3212
3212
  input_includes_cache_write: true
3213
+ - {provider: perplexity-agent, alias: perplexity/sonar, channel: perplexity-agent-api}
3213
3214
  prices:
3215
+ - channel: perplexity-agent-api
3216
+ region: global
3217
+ effective_from: "2026-11-18"
3218
+ input_per_mtok: 0.25
3219
+ output_per_mtok: 2.50
3220
+ cache_read_per_mtok: 0.0625
3221
+ rules: {input_includes_cache_read: true}
3222
+ source_url: https://docs.perplexity.ai/docs/agent-api/models
3214
3223
  - channel: perplexity-api
3215
3224
  region: global
3216
3225
  effective_from: "2025-04-18"
@@ -13976,6 +13985,21 @@ retrieval:
13976
13985
  per_1k_usd: 14.00
13977
13986
  effective_from: "2026-01-05"
13978
13987
  source_url: https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing
13988
+ # Agent API web-search invocations are distinct from legacy Sonar requests.
13989
+ - channel: perplexity-agent-api
13990
+ operation: web_search
13991
+ region: global
13992
+ unit: tool_call
13993
+ per_1k_usd: 2.50
13994
+ effective_from: "2026-11-18"
13995
+ source_url: https://docs.perplexity.ai/docs/agent-api/tools/web-search
13996
+ - channel: perplexity-agent-api
13997
+ operation: web_search_fast
13998
+ region: global
13999
+ unit: tool_call
14000
+ per_1k_usd: 1.00
14001
+ effective_from: "2026-11-18"
14002
+ source_url: https://docs.perplexity.ai/docs/agent-api/tools/web-search
13979
14003
  # Historical Sonar request fees end before the new API-specific rates.
13980
14004
  # The current Sonar fee is unverified, so its token row stays partial.
13981
14005
  - channel: perplexity-api
@@ -2,8 +2,10 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass
5
+ import re
6
+ from dataclasses import dataclass, field, fields as dataclass_fields
6
7
  from datetime import date, datetime, time, timezone
8
+ from difflib import get_close_matches
7
9
  from pathlib import Path
8
10
  from types import MappingProxyType
9
11
  from typing import Any, Iterable, Mapping
@@ -70,12 +72,80 @@ OFFER_GROUP_PROVIDERS = MappingProxyType(
70
72
  }
71
73
  )
72
74
  DEFAULT_MODEL_REGISTRY_PATH = Path(__file__).parent / "data" / "models.yaml"
75
+ TRAINING_ON_CUSTOMER_DATA = frozenset(
76
+ {"prohibited", "conditional", "permitted", "unknown"}
77
+ )
78
+ TRAINING_POLICY_FIELDS = frozenset(
79
+ {"training_on_customer_data", "source", "conditions"}
80
+ )
81
+ # A policy source is metadata, never fetched: an HTTPS URL on a DNS host, as
82
+ # sources.py accepts for price sources.
83
+ _HTTPS_URL = re.compile(r"https://[A-Za-z0-9.-]+(?::[0-9]+)?(?:/\S*)?")
84
+ # Where an effective training policy came from, most specific first.
85
+ TRAINING_POLICY_ORIGINS = ("route", "model", "provider", "unspecified")
73
86
 
74
87
 
75
88
  class ModelRegistryError(ValueError):
76
89
  """Raised when a model-registry document violates its contract."""
77
90
 
78
91
 
92
+ @dataclass(frozen=True, slots=True)
93
+ class TrainingPolicy:
94
+ """Whether a serving provider's default applicable terms let it train on
95
+ customer inputs and outputs, as published at ``source``.
96
+
97
+ ``prohibited`` means the default terms exclude training;
98
+ ``conditional`` means it depends on
99
+ ``conditions``, such as a paid tier or an opt-out; ``unknown`` means no
100
+ explicit promise was found. None of these verifies an account's
101
+ configuration."""
102
+
103
+ training_on_customer_data: str
104
+ source: str | None = None
105
+ conditions: str | None = None
106
+
107
+ def __post_init__(self) -> None:
108
+ for name in ("source", "conditions"):
109
+ text = getattr(self, name)
110
+ if text is not None and (not isinstance(text, str) or not text.strip()):
111
+ raise ModelRegistryError(f"{name} must be a nonblank string or None")
112
+ value = self.training_on_customer_data
113
+ if not isinstance(value, str) or value not in TRAINING_ON_CUSTOMER_DATA:
114
+ raise ModelRegistryError(
115
+ f"training_on_customer_data must be one of "
116
+ f"{sorted(TRAINING_ON_CUSTOMER_DATA)}, not {value!r}"
117
+ )
118
+ if self.source is None:
119
+ if value != "unknown":
120
+ raise ModelRegistryError(f"a {value} training policy needs a source")
121
+ elif not _HTTPS_URL.fullmatch(self.source):
122
+ raise ModelRegistryError("source must be an HTTPS URL")
123
+ if value == "conditional":
124
+ if self.conditions is None:
125
+ raise ModelRegistryError(
126
+ "a conditional training policy needs conditions"
127
+ )
128
+ elif self.conditions is not None:
129
+ raise ModelRegistryError(
130
+ f"a {value} training policy cannot have conditions"
131
+ )
132
+
133
+
134
+ @dataclass(frozen=True, slots=True)
135
+ class EffectiveTrainingPolicy:
136
+ """The training policy that applies to one route, the level it came from
137
+ (one of ``TRAINING_POLICY_ORIGINS``) and the registry version that
138
+ recorded it."""
139
+
140
+ policy: TrainingPolicy
141
+ origin: str
142
+ registry_version: str
143
+
144
+
145
+ UNKNOWN_TRAINING_POLICY = TrainingPolicy("unknown")
146
+ _NO_POLICIES: Mapping[str, Mapping[str, TrainingPolicy]] = MappingProxyType({})
147
+
148
+
79
149
  @dataclass(frozen=True, slots=True)
80
150
  class ModelRoute:
81
151
  key: str
@@ -86,6 +156,9 @@ class ModelRoute:
86
156
  model_id: str
87
157
  pricing_channel: str
88
158
  execution_profiles: tuple[str, ...]
159
+ # Replaces every inherited policy for this route when its service terms
160
+ # differ from the model's or the provider's.
161
+ training_policy: TrainingPolicy | None = None
89
162
 
90
163
 
91
164
  @dataclass(frozen=True, slots=True)
@@ -97,6 +170,12 @@ class ModelDefinition:
97
170
  routes: tuple[ModelRoute, ...]
98
171
  # The publisher's general-availability date, when recorded.
99
172
  released: date | None = None
173
+ # Serving provider -> pricing channel -> policy for this model's routes
174
+ # there, replacing that provider's default. Compared but not hashed, so
175
+ # a model stays hashable.
176
+ training_policy_overrides: Mapping[str, Mapping[str, TrainingPolicy]] = field(
177
+ default_factory=lambda: _NO_POLICIES, hash=False
178
+ )
100
179
 
101
180
 
102
181
  @dataclass(frozen=True, slots=True)
@@ -124,10 +203,44 @@ class ModelRegistry:
124
203
  routes: Mapping[str, ModelRoute]
125
204
  execution_profiles: Mapping[str, tuple[str, ...]]
126
205
  offer_groups: Mapping[str, OfferGroup]
206
+ # Serving provider -> pricing channel -> default policy, from the
207
+ # document's provider_defaults.
208
+ training_policy_defaults: Mapping[str, Mapping[str, TrainingPolicy]] = field(
209
+ default_factory=lambda: _NO_POLICIES
210
+ )
127
211
 
128
212
  def model(self, canonical_id: str) -> ModelDefinition:
129
213
  return self.models[canonical_id]
130
214
 
215
+ def effective_training_policy(self, route_key: str) -> EffectiveTrainingPolicy:
216
+ """The training policy for one route: the route's own policy, else the
217
+ model's override for the route's serving provider and channel, else
218
+ that provider and channel's default, else unknown. The first one
219
+ found replaces the rest whole, so an explicit unknown stops
220
+ inheritance. The publisher is never consulted: a model served by a
221
+ gateway or a cloud host follows that service's terms."""
222
+ route = self.routes[route_key]
223
+ candidates = (
224
+ ("route", route.training_policy),
225
+ (
226
+ "model",
227
+ self.models[route.canonical_id]
228
+ .training_policy_overrides.get(route.provider, {})
229
+ .get(route.pricing_channel),
230
+ ),
231
+ (
232
+ "provider",
233
+ self.training_policy_defaults.get(route.provider, {}).get(
234
+ route.pricing_channel
235
+ ),
236
+ ),
237
+ )
238
+ origin, policy = next(
239
+ ((origin, policy) for origin, policy in candidates if policy is not None),
240
+ ("unspecified", UNKNOWN_TRAINING_POLICY),
241
+ )
242
+ return EffectiveTrainingPolicy(policy, origin, self.version)
243
+
131
244
  def release_date(
132
245
  self, canonical_id: str, catalog: LoadedCatalog
133
246
  ) -> ReleaseDate | None:
@@ -214,6 +327,103 @@ def _unique_text_list(value: Any, field: str) -> tuple[str, ...]:
214
327
  return items
215
328
 
216
329
 
330
+ def _reject_fields(unknown: Iterable[Any], field: str) -> None:
331
+ extra = sorted(str(key) for key in unknown)
332
+ if extra:
333
+ raise ModelRegistryError(f"{field}: unknown field {extra[0]!r}")
334
+
335
+
336
+ _POLICY_PLACEMENT_FIELDS = (
337
+ "provider_defaults",
338
+ "training_policy_overrides",
339
+ "training_policy",
340
+ )
341
+ # Derive ordinary keys from the existing types, rather than maintain another
342
+ # schema list. Unknown keys still receive the full policy typo check.
343
+ _NON_POLICY_FIELDS = frozenset(
344
+ item.name
345
+ for model_type in (ModelRoute, ModelDefinition, ModelRegistry)
346
+ for item in dataclass_fields(model_type)
347
+ if item.name not in {
348
+ "training_policy", "training_policy_overrides", "training_policy_defaults"
349
+ }
350
+ )
351
+
352
+
353
+ def _reject_misspelled_policy_fields(
354
+ value: Mapping[str, Any], allowed: str, field: str
355
+ ) -> None:
356
+ """Other fields here are not checked, so older documents keep loading,
357
+ but a policy field misspelled or placed at the wrong level would
358
+ silently inherit a looser policy. Known ordinary fields skip similarity
359
+ checks; unknown keys retain the full check, including prefix typos."""
360
+ _reject_fields(
361
+ (
362
+ key
363
+ for key in value
364
+ if key != allowed
365
+ and key not in _NON_POLICY_FIELDS
366
+ and get_close_matches(str(key), _POLICY_PLACEMENT_FIELDS, n=1, cutoff=0.85)
367
+ ),
368
+ field,
369
+ )
370
+
371
+
372
+ def _training_policy(value: Any, field: str) -> TrainingPolicy:
373
+ policy = _mapping(value, field)
374
+ _reject_fields(set(policy) - TRAINING_POLICY_FIELDS, field)
375
+ conditions = policy.get("conditions")
376
+ if conditions is not None and not isinstance(conditions, str):
377
+ raise ModelRegistryError(f"{field} conditions must be a string")
378
+ parsed = {
379
+ "training_on_customer_data": _text(
380
+ policy.get("training_on_customer_data"),
381
+ f"{field} training_on_customer_data",
382
+ ),
383
+ "source": None
384
+ if policy.get("source") is None
385
+ else _text(policy["source"], f"{field} source"),
386
+ # Empty conditions read as none; a conditional policy then fails.
387
+ "conditions": (conditions or "").strip() or None,
388
+ }
389
+ try:
390
+ return TrainingPolicy(**parsed)
391
+ except ModelRegistryError as exc:
392
+ raise ModelRegistryError(f"{field}: {exc}") from None
393
+
394
+
395
+ def _provider_policies(
396
+ value: Any, field: str
397
+ ) -> Mapping[str, Mapping[str, TrainingPolicy]]:
398
+ """A serving provider -> pricing channel -> {training_policy: ...} map,
399
+ frozen to provider -> channel -> TrainingPolicy."""
400
+ providers: dict[str, Mapping[str, TrainingPolicy]] = {}
401
+ for provider, channels_value in _mapping(value, field).items():
402
+ if provider not in ROUTE_PROVIDERS:
403
+ raise ModelRegistryError(
404
+ f"{field}: unknown route provider {provider!r}"
405
+ )
406
+ channels: dict[str, TrainingPolicy] = {}
407
+ for channel, entry_value in _mapping(
408
+ channels_value, f"{field} {provider}"
409
+ ).items():
410
+ if channel != ROUTE_PROVIDER_CHANNELS[provider]:
411
+ raise ModelRegistryError(
412
+ f"{field}: provider {provider!r} cannot use pricing channel "
413
+ f"{channel!r}"
414
+ )
415
+ where = f"{field} {provider}/{channel}"
416
+ entry = _mapping(entry_value, where)
417
+ _reject_fields(set(entry) - {"training_policy"}, where)
418
+ if "training_policy" not in entry:
419
+ raise ModelRegistryError(f"{where}: needs training_policy")
420
+ channels[channel] = _training_policy(
421
+ entry["training_policy"], f"{where} training_policy"
422
+ )
423
+ providers[provider] = MappingProxyType(channels)
424
+ return MappingProxyType(providers)
425
+
426
+
217
427
  def _window_day(value: Any) -> date:
218
428
  """The calendar day a catalog price window starts, from a date or a
219
429
  timestamp as the catalog loader accepts them."""
@@ -261,6 +471,10 @@ def parse_model_registry(document: Any) -> ModelRegistry:
261
471
  root = _mapping(document, "models document")
262
472
  version = _text(root.get("version"), "models document version")
263
473
  _registry_version_date(version)
474
+ _reject_misspelled_policy_fields(root, "provider_defaults", "models document")
475
+ training_policy_defaults = _provider_policies(
476
+ root.get("provider_defaults", {}), "provider_defaults"
477
+ )
264
478
 
265
479
  models: dict[str, ModelDefinition] = {}
266
480
  routes: dict[str, ModelRoute] = {}
@@ -280,6 +494,13 @@ def parse_model_registry(document: Any) -> ModelRegistry:
280
494
  f"{canonical_id}: publisher {publisher!r} does not match canonical id"
281
495
  )
282
496
  released = _optional_date(model.get("released"), f"{canonical_id}: released")
497
+ _reject_misspelled_policy_fields(
498
+ model, "training_policy_overrides", canonical_id
499
+ )
500
+ training_policy_overrides = _provider_policies(
501
+ model.get("training_policy_overrides", {}),
502
+ f"{canonical_id}: training_policy_overrides",
503
+ )
283
504
  model_routes: list[ModelRoute] = []
284
505
  route_values = _list(model.get("routes", []), f"{canonical_id}: routes")
285
506
  for route_value in route_values:
@@ -327,6 +548,14 @@ def parse_model_registry(document: Any) -> ModelRegistry:
327
548
  f"{route_id}: duplicate physical route {physical_route!r}"
328
549
  )
329
550
  physical_routes.add(physical_route)
551
+ _reject_misspelled_policy_fields(route, "training_policy", route_key)
552
+ route_policy = (
553
+ _training_policy(
554
+ route["training_policy"], f"{route_key}: training_policy"
555
+ )
556
+ if "training_policy" in route
557
+ else None
558
+ )
330
559
  parsed = ModelRoute(
331
560
  key=route_key,
332
561
  id=route_id,
@@ -339,15 +568,25 @@ def parse_model_registry(document: Any) -> ModelRegistry:
339
568
  model_id=model_id,
340
569
  pricing_channel=pricing_channel,
341
570
  execution_profiles=profiles,
571
+ training_policy=route_policy,
342
572
  )
343
573
  routes[route_key] = parsed
344
574
  model_routes.append(parsed)
575
+ served = {(route.provider, route.pricing_channel) for route in model_routes}
576
+ for provider, channels in training_policy_overrides.items():
577
+ for channel in channels:
578
+ if (provider, channel) not in served:
579
+ raise ModelRegistryError(
580
+ f"{canonical_id}: training_policy_overrides "
581
+ f"{provider}/{channel} matches no route of the model"
582
+ )
345
583
  models[canonical_id] = ModelDefinition(
346
584
  canonical_id=canonical_id,
347
585
  display_name=display_name,
348
586
  publisher=publisher,
349
587
  routes=tuple(model_routes),
350
588
  released=released,
589
+ training_policy_overrides=training_policy_overrides,
351
590
  )
352
591
 
353
592
  execution_profiles: dict[str, tuple[str, ...]] = {}
@@ -441,6 +680,7 @@ def parse_model_registry(document: Any) -> ModelRegistry:
441
680
  routes=MappingProxyType(routes),
442
681
  execution_profiles=MappingProxyType(execution_profiles),
443
682
  offer_groups=MappingProxyType(offer_groups),
683
+ training_policy_defaults=training_policy_defaults,
444
684
  )
445
685
 
446
686
 
@@ -130,7 +130,7 @@ def count_search_units(row: Mapping[str, Any]) -> int | None:
130
130
  if count is not None:
131
131
  return count
132
132
  if str(row.get("provider") or "").strip().lower() in _PERPLEXITY:
133
- return 1
133
+ return None if row.get("retrieval_api") == "agent" else 1
134
134
  return _tool_items(row, _SEARCH_TOOL_TYPES)
135
135
 
136
136
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: metergraph-core
3
- Version: 0.8.22
3
+ Version: 0.8.25
4
4
  Summary: Open, effective-dated LLM pricing catalog and deterministic cost calculator for popular models across major providers and gateways, including OpenAI, Anthropic, Google Gemini, AWS Bedrock, OpenRouter, Vercel AI Gateway, and more.
5
5
  Author: Metergraph
6
6
  License-Expression: Apache-2.0
@@ -312,6 +312,35 @@ such as `priority` or `flex`, returns `partial` with `service_tier` in
312
312
  call from its final response or final usage chunk. Fees outside token usage,
313
313
  such as web search, are not included.
314
314
 
315
+ ### Complete costs from captured usage
316
+
317
+ `price_call_from_record()` accepts normalized SDK or relay usage, without reading
318
+ prompt or response content:
319
+
320
+ ```python
321
+ from metergraph_core import price_call_from_record
322
+
323
+ result = price_call_from_record({
324
+ "provider": "perplexity", "model": "perplexity/sonar",
325
+ "retrieval_api": "agent", "search_type": "web", "web_search_calls": 3,
326
+ "input_tokens": 1000, "output_tokens": 100, "ts": "2026-11-18T12:00:00Z",
327
+ })
328
+ print(result.status, result.cost_usd, result.retrieval_cost_usd)
329
+ ```
330
+
331
+ Core selects the API channel, retrieval operation, and billing unit. Supported
332
+ record evidence includes OpenAI search counts, Anthropic server-tool usage,
333
+ Google grounding queries, and Perplexity Agent standard/fast invocation counts.
334
+ Older Gemini grounded prompts do not inherit newer per-query rates. An unknown
335
+ rate, count, search type, or processing tier stays partial or unpriced.
336
+ `search_units` and `retrieval_cost_usd` expose the resolved components for storage.
337
+ `known_subtotal_usd` remains separate from a complete total.
338
+
339
+ A receiver that already resolved tokens against the same catalog may pass
340
+ `token_cost=`. Explicit API identity can select a different token channel; other
341
+ resolved token results are preserved. Qualified gateway totals can still be
342
+ reconciled separately with `resolve_billing()`.
343
+
315
344
  ## Model registry
316
345
 
317
346
  ```python
@@ -348,6 +377,84 @@ mismatches on any route, mismatched offer-group credentials/providers, and dupli
348
377
  remains exclusively in `prices.yaml`; being priceable does not automatically
349
378
  make a model an approved analysis candidate.
350
379
 
380
+ ### Training policy
381
+
382
+ `models.effective_training_policy(route_key)` says whether the route's
383
+ serving provider may train on customer inputs and outputs under its default
384
+ terms. It returns an `EffectiveTrainingPolicy` holding the `TrainingPolicy`,
385
+ the level it came from (`origin`) and the registry `version` that recorded
386
+ it. An unknown route key raises `KeyError`.
387
+
388
+ ```python
389
+ effective = models.effective_training_policy("default:openai/gpt-5.6-sol")
390
+ print(effective.policy.training_on_customer_data, effective.origin)
391
+ ```
392
+
393
+ `training_on_customer_data` is one of:
394
+
395
+ - `prohibited`: the default applicable terms exclude training on customer
396
+ inputs and outputs.
397
+ - `conditional`: training is excluded only when `conditions` hold, such as a
398
+ paid tier or an opt-out.
399
+ - `permitted`: the terms allow training.
400
+ - `unknown`: no explicit promise was found. A missing promise is `unknown`,
401
+ not `permitted`.
402
+
403
+ Every value except `unknown` cites an HTTPS `source`. Only `conditional` has
404
+ `conditions`. No value verifies an account’s configuration, opt-ins, or
405
+ separate agreements. The registry version and Git history record when a
406
+ policy changed.
407
+
408
+ The document records policies at three levels, keyed by the route's serving
409
+ `provider` and `pricing_channel`:
410
+
411
+ ```yaml
412
+ provider_defaults:
413
+ openai:
414
+ openai-api:
415
+ training_policy:
416
+ training_on_customer_data: prohibited
417
+ source: https://example.com/terms
418
+ models:
419
+ - canonical_id: example/model
420
+ training_policy_overrides: # this model on one provider and channel
421
+ vercel:
422
+ vercel-ai-gateway:
423
+ training_policy: {training_on_customer_data: unknown}
424
+ routes:
425
+ - key: default:example/model
426
+ training_policy: # this route only
427
+ training_on_customer_data: unknown
428
+ ```
429
+
430
+ The route's own `training_policy` wins. Otherwise the model's override for
431
+ the route's provider and channel applies, then that pair's provider default,
432
+ then `unknown` with origin `unspecified`. The first policy found replaces the
433
+ others whole, so an explicit `unknown` stops inheritance. The publisher is
434
+ never used. A gateway or cloud host such as `vercel` or `bedrock` follows its
435
+ own terms, not those of the model's publisher. The parser rejects unknown
436
+ policy fields, a provider/channel pair that no route could use, and a model
437
+ override for a pair the model has no route on. Documents without policies
438
+ still load, and every route resolves to `unknown`.
439
+
440
+ The bundled registry records a default for every serving provider. The YAML
441
+ is the source of truth for current policy values, sources and conditions:
442
+
443
+ ```python
444
+ for provider, channels in models.training_policy_defaults.items():
445
+ for channel, policy in channels.items():
446
+ print(provider, channel, policy.training_on_customer_data, policy.source)
447
+ ```
448
+
449
+ Adding a model normally requires no policy entry: it inherits the serving
450
+ provider's default. Add a model or route override only when its terms differ.
451
+ To update a provider policy, edit that one YAML object and increment the
452
+ existing registry version; source URLs and values are not duplicated in tests
453
+ or a documentation table. Changes still require review against the linked
454
+ official terms. There is no network lookup, scheduled refresher, extra
455
+ dependency or per-policy date to maintain. Policy lookup is explicit and does
456
+ not run during pricing or candidate selection.
457
+
351
458
  ## Billing evidence
352
459
 
353
460
  Servers can pass content-blind, already-extracted gateway fields through the