metergraphrelay 0.7.5__tar.gz → 0.7.7__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 (51) hide show
  1. {metergraphrelay-0.7.5/src/metergraphrelay.egg-info → metergraphrelay-0.7.7}/PKG-INFO +7 -1
  2. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/README.md +6 -0
  3. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/pyproject.toml +1 -1
  4. metergraphrelay-0.7.7/src/metergraphrelay/__init__.py +1 -0
  5. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/finish_reason.py +23 -0
  6. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/providers/braintrust.py +3 -0
  7. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/providers/langfuse.py +3 -0
  8. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/providers/langsmith.py +3 -0
  9. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/providers/openai.py +2 -0
  10. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/providers/phoenix.py +10 -0
  11. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/providers/portkey.py +43 -4
  12. metergraphrelay-0.7.7/src/metergraphrelay/providers/portkey_batch.py +127 -0
  13. metergraphrelay-0.7.7/src/metergraphrelay/reliability.py +139 -0
  14. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7/src/metergraphrelay.egg-info}/PKG-INFO +7 -1
  15. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay.egg-info/SOURCES.txt +3 -0
  16. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_portkey_sync.py +23 -0
  17. metergraphrelay-0.7.7/tests/test_reliability.py +88 -0
  18. metergraphrelay-0.7.5/src/metergraphrelay/__init__.py +0 -1
  19. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/LICENSE +0 -0
  20. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/setup.cfg +0 -0
  21. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/billing_evidence.py +0 -0
  22. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/capture_contract.py +0 -0
  23. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/cli.py +0 -0
  24. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/config.py +0 -0
  25. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/demo.py +0 -0
  26. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/http_limits.py +0 -0
  27. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/import_identity.py +0 -0
  28. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/metergraph_sync.py +0 -0
  29. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/portkey_sync.py +0 -0
  30. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/provider_sync.py +0 -0
  31. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/providers/__init__.py +0 -0
  32. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/providers/cache_shape.py +0 -0
  33. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/providers/portkey_export.py +0 -0
  34. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/push.py +0 -0
  35. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/py.typed +0 -0
  36. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/sync_core.py +0 -0
  37. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay/window.py +0 -0
  38. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay.egg-info/dependency_links.txt +0 -0
  39. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay.egg-info/entry_points.txt +0 -0
  40. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay.egg-info/requires.txt +0 -0
  41. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/src/metergraphrelay.egg-info/top_level.txt +0 -0
  42. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_billing_evidence.py +0 -0
  43. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_capture_contract.py +0 -0
  44. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_cli.py +0 -0
  45. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_config.py +0 -0
  46. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_demo.py +0 -0
  47. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_finish_reason.py +0 -0
  48. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_metergraph_sync.py +0 -0
  49. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_provider_sync.py +0 -0
  50. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_push.py +0 -0
  51. {metergraphrelay-0.7.5 → metergraphrelay-0.7.7}/tests/test_window.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: metergraphrelay
3
- Version: 0.7.5
3
+ Version: 0.7.7
4
4
  Summary: Move LLM trace data between systems: pull from providers, push to metergraph.
5
5
  Author: Vasiliy Radostev
6
6
  License-Expression: MIT
@@ -689,3 +689,9 @@ query itself is accepted — add:
689
689
 
690
690
  That live section is skipped whenever `BRAINTRUST_E2E_PROJECT` is unset, and
691
691
  never runs in CI.
692
+
693
+ ## Model reliability evidence
694
+
695
+ Relay extracts provider status, error codes, finish reasons and explicit refusal
696
+ signals before content conversion. Metergraph receivers use Core to classify
697
+ availability and refusals; Relay does not depend on Core or classify outcomes.
@@ -666,3 +666,9 @@ query itself is accepted — add:
666
666
 
667
667
  That live section is skipped whenever `BRAINTRUST_E2E_PROJECT` is unset, and
668
668
  never runs in CI.
669
+
670
+ ## Model reliability evidence
671
+
672
+ Relay extracts provider status, error codes, finish reasons and explicit refusal
673
+ signals before content conversion. Metergraph receivers use Core to classify
674
+ availability and refusals; Relay does not depend on Core or classify outcomes.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "metergraphrelay"
7
- version = "0.7.5"
7
+ version = "0.7.7"
8
8
  description = "Move LLM trace data between systems: pull from providers, push to metergraph."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1 @@
1
+ __version__ = "0.7.7"
@@ -105,3 +105,26 @@ def extract_phoenix_stop_reason(attributes: Mapping[str, Any]) -> str | None:
105
105
  if reason is not None:
106
106
  return reason
107
107
  return None
108
+
109
+
110
+ def extract_finish_reasons(value: Any, *, _depth: int = 0) -> list[str]:
111
+ """Preserve all reasons in documented export containers for the receiver."""
112
+ if _depth > _MAX_DEPTH:
113
+ return []
114
+ if isinstance(value, (list, tuple)):
115
+ return [reason for item in value for reason in extract_finish_reasons(item, _depth=_depth + 1)]
116
+ if not isinstance(value, Mapping):
117
+ return []
118
+ result = []
119
+ for key in _REASON_KEYS + ('finish_reasons', 'finishReasons'):
120
+ raw = value.get(key)
121
+ for item in raw if isinstance(raw, (list, tuple)) else (raw,):
122
+ reason = _string_reason(item)
123
+ if reason is not None:
124
+ result.append(reason)
125
+ incomplete = value.get('incomplete_details')
126
+ if isinstance(incomplete, Mapping) and _string_reason(incomplete.get('reason')):
127
+ result.append(incomplete['reason'])
128
+ for key in ('choices', 'candidates') + tuple(key for key in _REASON_CONTAINER_KEYS if key != 'incomplete_details'):
129
+ result.extend(extract_finish_reasons(value.get(key), _depth=_depth + 1))
130
+ return result
@@ -8,6 +8,7 @@ import urllib.error
8
8
  import urllib.request
9
9
  from typing import Any, Callable
10
10
 
11
+ from ..reliability import reliability_fields
11
12
  from .. import __version__
12
13
  from ..http_limits import ResponseTooLarge, read_bounded
13
14
  from ..billing_evidence import reported_cost
@@ -545,6 +546,8 @@ def normalize_span(
545
546
  row["import_source"] = import_context.source
546
547
  row["import_source_scope"] = import_context.source_scope
547
548
  row["import_event_id"] = canonical_import_event_id(span.get("id"))
549
+ row.update(reliability_fields(provider=row.get("provider"), response=span.get("output"),
550
+ error=raw_error if isinstance(raw_error, dict) else None, http_status_code=None, finish_reason=stop_reason))
548
551
  return capture_row(row)
549
552
 
550
553
 
@@ -10,6 +10,7 @@ import urllib.parse
10
10
  import urllib.request
11
11
  from typing import Any, Callable
12
12
 
13
+ from ..reliability import reliability_fields
13
14
  from .. import __version__
14
15
  from .cache_shape import CACHE_EXCLUSIVE_INPUT_PROVIDERS
15
16
  from ..http_limits import ResponseTooLarge, read_bounded
@@ -472,6 +473,8 @@ def normalize_observation(
472
473
  row["import_source"] = import_context.source
473
474
  row["import_source_scope"] = import_context.source_scope
474
475
  row["import_event_id"] = canonical_import_event_id(observation.get("id"))
476
+ row.update(reliability_fields(provider=provider, response=observation.get("output"),
477
+ error=None, http_status_code=None, finish_reason=stop_reason))
475
478
  return capture_row(row)
476
479
 
477
480
 
@@ -38,6 +38,7 @@ import urllib.request
38
38
  from datetime import datetime
39
39
  from typing import Any, Callable
40
40
 
41
+ from ..reliability import reliability_fields
41
42
  from .. import __version__
42
43
  from ..http_limits import ResponseTooLarge, read_bounded
43
44
  from ..billing_evidence import reported_cost
@@ -503,6 +504,8 @@ def normalize_run(
503
504
  row["import_source"] = import_context.source
504
505
  row["import_source_scope"] = import_context.source_scope
505
506
  row["import_event_id"] = canonical_import_event_id(run.get("id"))
507
+ row.update(reliability_fields(provider=row.get("provider"), response=run.get("outputs"),
508
+ error=None, http_status_code=None, finish_reason=stop_reason))
506
509
  return capture_row(row)
507
510
 
508
511
 
@@ -6,6 +6,7 @@ from datetime import datetime, timezone
6
6
  from itertools import islice
7
7
  from typing import Any, Iterable
8
8
 
9
+ from ..reliability import reliability_fields
9
10
  from .. import __version__
10
11
  from ..capture_contract import capture_response_text, capture_row, capture_tool_calls
11
12
 
@@ -93,6 +94,7 @@ def normalize_completion(
93
94
  )
94
95
 
95
96
  return capture_row({
97
+ **reliability_fields(provider="openai", response=completion),
96
98
  "ts": ts,
97
99
  "provider": "openai",
98
100
  "model": completion.model,
@@ -33,6 +33,7 @@ import urllib.request
33
33
  from datetime import datetime
34
34
  from typing import Any, Callable
35
35
 
36
+ from ..reliability import reliability_fields
36
37
  from .. import __version__
37
38
  from ..http_limits import ResponseTooLarge, read_bounded
38
39
  from ..capture_contract import capture_response_text, capture_row
@@ -360,6 +361,10 @@ def normalize_span(
360
361
  else None
361
362
  )
362
363
 
364
+ reported_error = attributes.get("error.type")
365
+ if error and isinstance(reported_error, str) and reported_error:
366
+ error_type = reported_error
367
+
363
368
  request_json, request_text = _map_input(attributes)
364
369
  stop_reason = extract_phoenix_stop_reason(attributes)
365
370
  context = span.get("context")
@@ -399,12 +404,17 @@ def normalize_span(
399
404
  }
400
405
  if stop_reason is not None:
401
406
  row["stop_reason"] = stop_reason
407
+ reasons = attributes.get("gen_ai.response.finish_reasons")
408
+ if isinstance(reasons, (list, tuple)) and all(isinstance(reason, str) for reason in reasons):
409
+ row["otel"] = {"finish_reasons": list(reasons)}
402
410
  if import_context is not None:
403
411
  # The OpenTelemetry span id is stable across re-reads of the same
404
412
  # span, so an overlap re-pull deduplicates on the server.
405
413
  row["import_source"] = import_context.source
406
414
  row["import_source_scope"] = import_context.source_scope
407
415
  row["import_event_id"] = canonical_import_event_id(span_id)
416
+ row.update(reliability_fields(provider=row.get("provider"), response=None,
417
+ error=None, attributes=attributes, finish_reason=stop_reason))
408
418
  return capture_row(row)
409
419
 
410
420
 
@@ -9,6 +9,7 @@ from decimal import Decimal
9
9
  from datetime import datetime, timedelta, timezone
10
10
  from typing import Any, Callable
11
11
 
12
+ from ..reliability import reliability_fields
12
13
  from .. import __version__
13
14
  from ..billing_evidence import reported_cost
14
15
  from ..capture_contract import capture_row, capture_text, capture_tool_calls
@@ -545,9 +546,46 @@ def normalize_portkey_row(
545
546
  result["import_source"] = import_context.source
546
547
  result["import_source_scope"] = import_context.source_scope
547
548
  result["import_event_id"] = import_event_id # validated, stripped id
549
+ result.update(reliability_fields(provider=row.get("ai_org"), response=response,
550
+ error=response.get("error") if is_error else None, http_status_code=status_code, finish_reason=stop_reason))
548
551
  return capture_row(result)
549
552
 
550
553
 
554
+ def normalize_portkey_rows(
555
+ row: dict, *, import_context: ImportContext | None = None,
556
+ batch_requests: dict[str, dict] | None = None,
557
+ ) -> list[dict]:
558
+ """Normalize one export row to zero or more individual inference outcomes.
559
+
560
+ Ordinary rows keep the singular converter's contract. Batch management is
561
+ excluded; result messages use native usage and stable per-message identity.
562
+ The optional request map must belong to this batch, keyed by custom_id.
563
+ """
564
+ from .portkey_batch import BatchShapeError, expand_batch
565
+
566
+ try:
567
+ children = expand_batch(row, batch_requests=batch_requests)
568
+ except BatchShapeError as exc:
569
+ raise PortkeyConversionError(str(exc)) from None
570
+ if children is None:
571
+ return [normalize_portkey_row(row, import_context=import_context)]
572
+ results = []
573
+ for child in children:
574
+ result = normalize_portkey_row(child, import_context=import_context)
575
+ if child.get('request') is None:
576
+ result.pop('request_json', None)
577
+ result['batch'] = True
578
+ result['endpoint'] = 'messages'
579
+ result['batch_custom_id'] = child['batch_custom_id']
580
+ result['batch_outcome'] = child['batch_outcome']
581
+ result['portkey_export_id'] = row.get('id')
582
+ # These describe a whole download, not an individual model completion.
583
+ for key in ('cost_usd', 'reported_cost_usd', 'reported_cost_source', 'latency_ms'):
584
+ result.pop(key, None)
585
+ results.append(result)
586
+ return results
587
+
588
+
551
589
  def convert_portkey_export(
552
590
  input_path: str,
553
591
  output_path: str,
@@ -582,8 +620,8 @@ def convert_portkey_export(
582
620
  )
583
621
  continue
584
622
  try:
585
- normalized = normalize_portkey_row(row, import_context=import_context)
586
- serialized = json.dumps(normalized)
623
+ normalized_rows = normalize_portkey_rows(row, import_context=import_context)
624
+ serialized_rows = [json.dumps(normalized) for normalized in normalized_rows]
587
625
  except (KeyError, TypeError, AttributeError) as exc:
588
626
  skipped += 1
589
627
  row_id = (
@@ -594,6 +632,7 @@ def convert_portkey_export(
594
632
  file=sys.stderr,
595
633
  )
596
634
  continue
597
- dst.write(serialized + "\n")
598
- converted += 1
635
+ for serialized in serialized_rows:
636
+ dst.write(serialized + "\n")
637
+ converted += 1
599
638
  return converted, skipped
@@ -0,0 +1,127 @@
1
+ """Identify Anthropic batch operations and expand their individual outcomes.
2
+
3
+ The download is transport, not inference: its cost, latency and token counters
4
+ cannot be assigned to any child message. Successful message IDs are the stable
5
+ identity even when an application downloads the same results more than once.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from typing import Any
12
+
13
+
14
+ class BatchShapeError(ValueError):
15
+ pass
16
+
17
+
18
+ _CONTROL = re.compile(r"(?:anthropic/)?(?:batches|msgbatch_[A-Za-z0-9_-]+)(?:/cancel)?\Z")
19
+ _RESULTS = re.compile(r"(?:anthropic/)?(?:results|msgbatch_[A-Za-z0-9_-]+/results)\Z")
20
+ _RESULT_BATCH = re.compile(r"(?:anthropic/)?(?P<batch>msgbatch_[A-Za-z0-9_-]+)/results\Z")
21
+
22
+
23
+ def _validate_cache(usage: dict) -> None:
24
+ for key in ('cache_read_input_tokens', 'cache_creation_input_tokens'):
25
+ if key in usage and (type(usage[key]) is not int or usage[key] < 0):
26
+ raise BatchShapeError('invalid batch message cache usage')
27
+ if 'cache_creation' in usage:
28
+ creation = usage['cache_creation']
29
+ if not isinstance(creation, dict):
30
+ raise BatchShapeError('invalid batch message cache usage')
31
+ for key in ('ephemeral_5m_input_tokens', 'ephemeral_1h_input_tokens'):
32
+ if key in creation and (type(creation[key]) is not int or creation[key] < 0):
33
+ raise BatchShapeError('invalid batch message cache usage')
34
+
35
+
36
+ def _envelopes(response: Any) -> list[dict]:
37
+ if isinstance(response, str):
38
+ try:
39
+ response = [json.loads(line) for line in response.splitlines() if line.strip()]
40
+ except (ValueError, RecursionError):
41
+ raise BatchShapeError('invalid Anthropic batch results JSONL') from None
42
+ if len(response) == 1 and isinstance(response[0], list):
43
+ response = response[0]
44
+ if isinstance(response, dict):
45
+ response = [response]
46
+ if not isinstance(response, list) or not response:
47
+ raise BatchShapeError('Anthropic batch results must contain outcomes')
48
+ if not all(isinstance(item, dict) for item in response):
49
+ raise BatchShapeError('invalid Anthropic batch result envelope')
50
+ return response
51
+
52
+
53
+ def expand_batch(row: dict, *, batch_requests: dict | None = None) -> list[dict] | None:
54
+ """Return ordinary-shaped Portkey child rows, [] for control, None otherwise.
55
+
56
+ Request correlation is supplied by a caller that knows the batch identity.
57
+ Joining custom_id across an arbitrary export would mix unrelated batches.
58
+ """
59
+ if str(row.get('ai_org', '')).strip().lower() != 'anthropic':
60
+ return None
61
+ response = row.get('response')
62
+ model = str(row.get('ai_model') or '')
63
+ if (isinstance(response, dict) and response.get('type') == 'message_batch') or _CONTROL.fullmatch(model):
64
+ return []
65
+ envelope = isinstance(response, dict) and 'custom_id' in response and 'result' in response
66
+ if not envelope and not _RESULTS.fullmatch(model):
67
+ return None
68
+ status = row.get('response_status_code')
69
+ if type(status) is not int or not 200 <= status < 300:
70
+ # A failed/not-ready fetch is batch transport, just like status polls.
71
+ # Only a successful response can claim to contain inference results.
72
+ return []
73
+
74
+ expanded = []
75
+ seen = set()
76
+ for item in _envelopes(response):
77
+ custom_id = item.get('custom_id')
78
+ outcome = item.get('result')
79
+ if not isinstance(custom_id, str) or not custom_id or not isinstance(outcome, dict):
80
+ raise BatchShapeError('invalid Anthropic batch result envelope')
81
+ if custom_id in seen:
82
+ raise BatchShapeError('duplicate custom_id in Anthropic batch results')
83
+ seen.add(custom_id)
84
+ request = (batch_requests or {}).get(custom_id)
85
+ if request is not None and not isinstance(request, dict):
86
+ raise BatchShapeError('invalid correlated Anthropic batch request')
87
+ outcome_type = outcome.get('type')
88
+ if outcome_type == 'succeeded':
89
+ message = outcome.get('message')
90
+ if not isinstance(message, dict) or message.get('type') != 'message':
91
+ raise BatchShapeError('successful batch outcome is missing a message')
92
+ message_id, actual_model, usage = message.get('id'), message.get('model'), message.get('usage')
93
+ if not isinstance(message_id, str) or not message_id.strip():
94
+ raise BatchShapeError('successful batch message is missing its identity')
95
+ if not isinstance(actual_model, str) or not actual_model.strip() or not isinstance(usage, dict):
96
+ raise BatchShapeError('successful batch message is missing model or usage')
97
+ for field in ('input_tokens', 'output_tokens'):
98
+ if type(usage.get(field)) is not int or usage[field] < 0:
99
+ raise BatchShapeError('invalid batch message token usage')
100
+ _validate_cache(usage)
101
+ identity = 'anthropic-batch:' + message_id.strip()
102
+ status = 200
103
+ elif outcome_type in ('errored', 'canceled', 'expired'):
104
+ actual_model = request.get('model') if request else None
105
+ usage = {}
106
+ batch_id = row.get('batch_id')
107
+ endpoint_batch = _RESULT_BATCH.fullmatch(model)
108
+ if not batch_id and endpoint_batch:
109
+ batch_id = endpoint_batch['batch']
110
+ # Without a provider batch ID, the export ID is the only available
111
+ # stable boundary. Never deduplicate unrelated batches by custom_id.
112
+ boundary = batch_id if isinstance(batch_id, str) and batch_id else row.get('id')
113
+ if not isinstance(boundary, str) or not boundary.strip():
114
+ raise BatchShapeError('failed batch outcome is missing its identity')
115
+ identity = 'anthropic-batch:' + boundary.strip() + ':' + custom_id
116
+ message = {'error': outcome.get('error') or {'type': outcome_type, 'message': outcome_type}}
117
+ status = 400
118
+ else:
119
+ raise BatchShapeError('unknown Anthropic batch outcome type')
120
+ expanded.append({
121
+ **row, 'id': identity, 'ai_model': actual_model, 'request': request,
122
+ 'response': message, 'response_status_code': status,
123
+ 'req_units': usage.get('input_tokens'), 'res_units': usage.get('output_tokens'),
124
+ 'cost': None, 'response_time': None, 'batch_custom_id': custom_id,
125
+ 'batch_outcome': outcome_type,
126
+ })
127
+ return expanded
@@ -0,0 +1,139 @@
1
+ """Extract content-free provider facts for receiver-owned classification."""
2
+ from typing import Any
3
+
4
+ from .finish_reason import extract_finish_reasons, extract_stop_reason
5
+
6
+
7
+ def _native_response(value: Any) -> Any:
8
+ """Unwrap documented message/generation containers before text extraction."""
9
+ if isinstance(value, dict):
10
+ if any(key in value for key in ('choices', 'candidates', 'output', 'stop_reason')):
11
+ return value
12
+ if 'generations' in value:
13
+ return _native_response(value['generations'])
14
+ if 'message' in value:
15
+ message = value['message']
16
+ message = message.get('kwargs', message) if isinstance(message, dict) else message
17
+ result = _native_response(message)
18
+ if isinstance(result, dict) and 'choices' in result:
19
+ finish = extract_stop_reason(value)
20
+ for choice in result['choices']:
21
+ choice['finish_reason'] = finish or choice.get('finish_reason')
22
+ return result
23
+ if value.get('role') == 'assistant' or 'additional_kwargs' in value:
24
+ message = dict(value)
25
+ extra = value.get('additional_kwargs')
26
+ if isinstance(extra, dict) and extra.get('refusal') is not None:
27
+ message['refusal'] = extra['refusal']
28
+ return {'choices': [{'message': message, 'finish_reason': extract_stop_reason(value)}]}
29
+ if isinstance(value, (list, tuple)):
30
+ choices = []
31
+ for item in value:
32
+ native = _native_response(item)
33
+ if isinstance(native, dict) and isinstance(native.get('choices'), list):
34
+ choices.extend(native['choices'])
35
+ else:
36
+ choices.append({})
37
+ if any(choice for choice in choices):
38
+ return {'choices': choices}
39
+ return value
40
+
41
+
42
+
43
+ def _get(value: Any, key: str, default: Any = None) -> Any:
44
+ return value.get(key, default) if isinstance(value, dict) else getattr(value, key, default)
45
+
46
+
47
+ def _items(value: Any) -> list | tuple:
48
+ return value if isinstance(value, (list, tuple)) else ()
49
+
50
+
51
+ def _string(value: Any) -> str | None:
52
+ return value[:256] if isinstance(value, str) and value else None
53
+
54
+
55
+ def reliability_fields(*, provider: str | None = None, response: Any = None,
56
+ error: Any = None, http_status_code: Any = None,
57
+ finish_reason: str | None = None,
58
+ attributes: dict | None = None) -> dict:
59
+ """Keep native signals before text conversion; do not infer provider outcomes."""
60
+ source_reasons = extract_finish_reasons(response)
61
+ response = _native_response(response)
62
+ attributes = attributes or {}
63
+ payload = _get(error, 'error', _get(error, 'body', error))
64
+ payload = _get(payload, 'error', payload)
65
+ code = http_status_code
66
+ if code is None:
67
+ code = attributes.get('http.response.status_code', attributes.get('http.status_code'))
68
+ if code is None:
69
+ code = (_get(error, 'status_code') or _get(error, 'status') or _get(error, 'statusCode')
70
+ or _get(_get(error, 'response'), 'status_code') or _get(response, 'status_code'))
71
+ reasons = []
72
+ def reason(value):
73
+ value = _string(value)
74
+ if value is not None:
75
+ reasons.append(value)
76
+ for value in _items(attributes.get('gen_ai.response.finish_reasons')):
77
+ reason(value)
78
+ if not reasons:
79
+ reason(attributes.get('llm.finish_reason'))
80
+ if not reasons:
81
+ reasons.extend(source_reasons)
82
+ if not reasons:
83
+ reason(_get(response, 'stop_reason'))
84
+ reason(_get(response, 'finish_reason'))
85
+ reason(_get(_get(response, 'incomplete_details'), 'reason'))
86
+ feedback = _get(response, 'promptFeedback', _get(response, 'prompt_feedback'))
87
+ reason(_get(feedback, 'blockReason', _get(feedback, 'block_reason')))
88
+ signal = None
89
+ received = (any(isinstance(_get(response, key), (list, tuple)) for key in ('choices', 'candidates', 'output'))
90
+ or feedback is not None
91
+ or _get(response, 'stop_reason') is not None and isinstance(_get(response, 'content'), (list, tuple)))
92
+ inspected = []
93
+ for choice in _items(_get(response, 'choices')):
94
+ if not source_reasons:
95
+ reason(_get(choice, 'finish_reason'))
96
+ message = _get(choice, 'message')
97
+ if _get(message, 'refusal'):
98
+ signal = True
99
+ inspected.append(message is not None and _string(_get(choice, 'finish_reason')) is not None and (
100
+ _get(message, 'content') is not None or _get(message, 'tool_calls') is not None
101
+ or isinstance(message, dict) and 'refusal' in message
102
+ or not isinstance(message, dict) and hasattr(message, 'refusal')))
103
+ output = _get(response, 'output')
104
+ for item in _items(output):
105
+ parts = _get(item, 'content')
106
+ kind = _get(item, 'type')
107
+ if kind == 'refusal' or any(_get(part, 'type') == 'refusal' for part in _items(parts)):
108
+ signal = True
109
+ inspected.append(_get(response, 'status') in {'completed', 'incomplete'} and (
110
+ kind in {'function_call', 'reasoning'} or (
111
+ kind == 'message' and bool(_items(parts)) and all(
112
+ _get(part, 'type') in {'output_text', 'refusal'} for part in _items(parts)))))
113
+ content = _get(response, 'content')
114
+ if _get(response, 'stop_reason') is not None and isinstance(content, (list, tuple)):
115
+ if any(_get(part, 'type') == 'refusal' for part in content):
116
+ signal = True
117
+ inspected.append(bool(content) and all(_get(part, 'type') in {
118
+ 'text', 'tool_use', 'thinking', 'redacted_thinking', 'refusal'} for part in content))
119
+ for candidate in _items(_get(response, 'candidates')):
120
+ if not source_reasons:
121
+ reason(_get(candidate, 'finishReason', _get(candidate, 'finish_reason')))
122
+ inspected.append(_string(_get(candidate, 'finishReason', _get(candidate, 'finish_reason'))) is not None
123
+ and bool(_items(_get(_get(candidate, 'content'), 'parts'))))
124
+ if not reasons:
125
+ reason(finish_reason)
126
+ if signal is None and inspected and all(inspected):
127
+ signal = False
128
+ row = {
129
+ 'http_status_code': code if type(code) is int and 100 <= code <= 599 else None,
130
+ 'error_code': _string(_get(payload, 'code')),
131
+ 'refusal_signal': signal,
132
+ 'response_received': True if received else None,
133
+ }
134
+ error_type = attributes.get('error.type') or _get(payload, 'type') or _get(error, 'name')
135
+ if _string(error_type):
136
+ row['error_type'] = _string(error_type)
137
+ if reasons:
138
+ row['otel'] = {'finish_reasons': reasons}
139
+ return row
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: metergraphrelay
3
- Version: 0.7.5
3
+ Version: 0.7.7
4
4
  Summary: Move LLM trace data between systems: pull from providers, push to metergraph.
5
5
  Author: Vasiliy Radostev
6
6
  License-Expression: MIT
@@ -689,3 +689,9 @@ query itself is accepted — add:
689
689
 
690
690
  That live section is skipped whenever `BRAINTRUST_E2E_PROJECT` is unset, and
691
691
  never runs in CI.
692
+
693
+ ## Model reliability evidence
694
+
695
+ Relay extracts provider status, error codes, finish reasons and explicit refusal
696
+ signals before content conversion. Metergraph receivers use Core to classify
697
+ availability and refusals; Relay does not depend on Core or classify outcomes.
@@ -15,6 +15,7 @@ src/metergraphrelay/portkey_sync.py
15
15
  src/metergraphrelay/provider_sync.py
16
16
  src/metergraphrelay/push.py
17
17
  src/metergraphrelay/py.typed
18
+ src/metergraphrelay/reliability.py
18
19
  src/metergraphrelay/sync_core.py
19
20
  src/metergraphrelay/window.py
20
21
  src/metergraphrelay.egg-info/PKG-INFO
@@ -31,6 +32,7 @@ src/metergraphrelay/providers/langsmith.py
31
32
  src/metergraphrelay/providers/openai.py
32
33
  src/metergraphrelay/providers/phoenix.py
33
34
  src/metergraphrelay/providers/portkey.py
35
+ src/metergraphrelay/providers/portkey_batch.py
34
36
  src/metergraphrelay/providers/portkey_export.py
35
37
  tests/test_billing_evidence.py
36
38
  tests/test_capture_contract.py
@@ -42,4 +44,5 @@ tests/test_metergraph_sync.py
42
44
  tests/test_portkey_sync.py
43
45
  tests/test_provider_sync.py
44
46
  tests/test_push.py
47
+ tests/test_reliability.py
45
48
  tests/test_window.py
@@ -184,6 +184,29 @@ def _run(mg, pk, pushes, **overrides):
184
184
  # -- _LeaseRenewer: time-based renewal policy ------------------------------
185
185
 
186
186
 
187
+ @pytest.mark.parametrize('status', [None, 404, 429, 500])
188
+ def test_failed_batch_results_fetch_does_not_block_checkpoint(status):
189
+ mg, pushes = FakeMeterGraph(_acquired()), []
190
+ pending = {**_portkey_row('not-ready'), 'ai_org': 'anthropic',
191
+ 'ai_model': 'anthropic/results', 'response_status_code': status,
192
+ 'response': {'error': {'type': 'not_found_error'}}}
193
+ pk = FakePortkey({(WINDOW_START, WINDOW_END): [pending, _portkey_row('real-call')]})
194
+ outcome = _run(mg, pk, pushes)
195
+ assert outcome.status == 'completed'
196
+ assert mg.completed == ['lease-1'] and mg.abandoned == []
197
+ assert [row['request_id'] for push in pushes for row in push['rows']] == ['real-call']
198
+
199
+
200
+ def test_corrupt_successful_batch_results_still_blocks_checkpoint():
201
+ mg, pushes = FakeMeterGraph(_acquired()), []
202
+ corrupt = {**_portkey_row('corrupt-download'), 'ai_org': 'anthropic',
203
+ 'ai_model': 'anthropic/results', 'response': 'not-json'}
204
+ pk = FakePortkey({(WINDOW_START, WINDOW_END): [corrupt]})
205
+ outcome = _run(mg, pk, pushes)
206
+ assert outcome.status == 'failed'
207
+ assert mg.completed == [] and mg.abandoned == ['lease-1']
208
+
209
+
187
210
  def test_lease_renewer_does_not_renew_before_interval_elapses():
188
211
  clock = FakeClock()
189
212
  renews = []
@@ -0,0 +1,88 @@
1
+ """Evidence extraction must not change import identity or accounting."""
2
+
3
+ import pytest
4
+ from metergraphrelay.providers.portkey import normalize_portkey_row
5
+
6
+ @pytest.mark.parametrize('status,response,error_code,signal', [
7
+ (429, {'error': {'code': 'rate_limit_exceeded'}}, 'rate_limit_exceeded', None),
8
+ (503, {'error': {'message': 'retry later'}}, None, None),
9
+ (401, {'error': {'code': 'invalid_api_key'}}, 'invalid_api_key', None),
10
+ (200, {'choices': [{'finish_reason': 'content_filter','message': {'content': None}}]}, None, None),
11
+ (200, {'choices': [{'finish_reason': 'stop','message': {'content': 'ok', 'refusal': None}}]}, None, False),
12
+ (200, {'usage': {'total_tokens': 4}}, None, None),
13
+ ])
14
+ def test_portkey_evidence_preserves_identity_and_accounting(status,response,error_code,signal):
15
+ source = {'id':'request-1','trace_id':'trace-1','created_at':'2026-11-01T00:00:00Z',
16
+ 'ai_org':'openai','ai_model':'example-model','cost':1,'req_units':3,'res_units':1,
17
+ 'response_time':25,'response_status_code':status,'request':{},'response':response}
18
+ row = normalize_portkey_row(source)
19
+ assert row['http_status_code'] == status
20
+ assert row['error_code'] == error_code
21
+ assert row['refusal_signal'] is signal
22
+ assert 'availability' not in row and 'refused' not in row
23
+ assert row['request_id'] == 'request-1'
24
+ assert row['input_tokens'] == 3 and row['output_tokens'] == 1
25
+ assert row['cost_usd'] == '0.01'
26
+ assert row['latency_ms'] == 25
27
+
28
+
29
+ def test_other_import_does_not_infer_non_refusal_from_success():
30
+ from metergraphrelay.providers.braintrust import normalize_span
31
+ row = normalize_span({'id':'span-1','created':'2026-11-01T00:00:00Z',
32
+ 'metadata': {'model':'example-model'}, 'metrics': {}, 'output': 'ok',
33
+ 'span_attributes': {'type':'llm'}, 'input': 'input'}, route_override=None)
34
+ assert row['refusal_signal'] is None
35
+ assert row['response_received'] is None
36
+ assert 'availability' not in row and 'refused' not in row
37
+
38
+
39
+ def test_langchain_refusal_is_preserved_before_content_conversion():
40
+ from metergraphrelay.reliability import reliability_fields
41
+ output = {'generations': [[{'generation_info': {'finish_reason': 'stop'},
42
+ 'message': {'kwargs': {'content': '', 'additional_kwargs': {'refusal': 'policy'}}}}]]}
43
+ assert reliability_fields(response=output, finish_reason='stop')['refusal_signal'] is True
44
+
45
+
46
+ def test_list_message_refusal_is_preserved_before_content_conversion():
47
+ from metergraphrelay.reliability import reliability_fields
48
+ assert reliability_fields(response=[{'role':'assistant','content':None,'refusal':'policy'}])['refusal_signal'] is True
49
+
50
+
51
+ def test_all_import_adapters_preserve_explicit_refusal():
52
+ from types import SimpleNamespace as NS
53
+ from metergraphrelay.providers.langfuse import normalize_observation
54
+ from metergraphrelay.providers.langsmith import normalize_run
55
+ from metergraphrelay.providers.braintrust import normalize_span as braintrust_span
56
+ from metergraphrelay.providers.phoenix import normalize_span as phoenix_span
57
+ from metergraphrelay.providers.openai import normalize_completion
58
+ response = {'choices':[{'finish_reason':'stop','message':{'content':None,'refusal':'policy'}}]}
59
+ rows = [
60
+ normalize_observation({'id':'obs-1','traceId':'trace-1','startTime':'2026-11-01T00:00:00Z',
61
+ 'model':'example-model','output':response},route_override=None),
62
+ normalize_run({'id':'run-1','start_time':'2026-11-01T00:00:00Z',
63
+ 'outputs':{'generations':[[{'generation_info':{'finish_reason':'stop'},'message':{
64
+ 'kwargs':{'content':'','additional_kwargs':{'refusal':'policy'}}}}]]}},route_override=None),
65
+ braintrust_span({'id':'span-1','created':'2026-11-01T00:00:00Z','metrics':{},
66
+ 'output':[{'role':'assistant','content':None,'refusal':'policy'}]},route_override=None),
67
+ phoenix_span({'id':'span-1','start_time':'2026-11-01T00:00:00Z', 'status_code':'ERROR',
68
+ 'attributes':{'gen_ai.response.finish_reasons':['stop', 'content_filter'],
69
+ 'error.type':'provider_policy_block'}},project='synthetic',route_override=None),
70
+ normalize_completion(NS(created=1,id='completion-1',model='example-model',
71
+ choices=[NS(finish_reason='stop',message=NS(content=None,refusal='policy'))]), [],
72
+ route='synthetic',include_content=False),
73
+ ]
74
+ for row in rows:
75
+ assert 'availability' not in row and 'refused' not in row
76
+ for row in rows[:3] + rows[4:]:
77
+ assert row['refusal_signal'] is True
78
+ assert rows[3]['refusal_signal'] is None
79
+
80
+ assert rows[-2]['error_type'] == 'provider_policy_block'
81
+ assert rows[-2]['otel']['finish_reasons'] == ['stop', 'content_filter']
82
+
83
+
84
+ def test_sparse_and_multi_choice_evidence_stays_conservative():
85
+ from metergraphrelay.reliability import reliability_fields
86
+ assert reliability_fields(response={'choices': [{'message': {'content': 'ok'}}]})['refusal_signal'] is None
87
+ assert reliability_fields(response=[{'role': 'assistant', 'content': 'ok', 'finish_reason': 'stop'}, {}])['refusal_signal'] is None
88
+ assert reliability_fields(response={'finish_reasons': ['stop', 'content_filter']}, finish_reason='stop')['otel']['finish_reasons'] == ['stop', 'content_filter']
@@ -1 +0,0 @@
1
- __version__ = "0.7.5"
File without changes