inferenceledger 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.
- inference_engine/__init__.py +3 -0
- inference_engine/adapters/api/__init__.py +2 -0
- inference_engine/adapters/api/app.py +31 -0
- inference_engine/adapters/api/routes/__init__.py +2 -0
- inference_engine/adapters/api/routes/inference.py +106 -0
- inference_engine/application/__init__.py +2 -0
- inference_engine/application/dto/__init__.py +2 -0
- inference_engine/application/dto/batch_dto.py +16 -0
- inference_engine/application/dto/inference_dto.py +21 -0
- inference_engine/application/dto/metrics_dto.py +12 -0
- inference_engine/application/services/__init__.py +2 -0
- inference_engine/application/services/benchmarking/__init__.py +24 -0
- inference_engine/application/services/benchmarking/litellm_arm_service.py +406 -0
- inference_engine/application/services/benchmarking/migration_decision_service.py +383 -0
- inference_engine/application/services/benchmarking/run_evidence_service.py +169 -0
- inference_engine/application/services/cache/__init__.py +2 -0
- inference_engine/application/services/cache/cache_service.py +94 -0
- inference_engine/application/services/cache/warmup_service.py +39 -0
- inference_engine/application/services/inference/__init__.py +2 -0
- inference_engine/application/services/inference/batch_service.py +36 -0
- inference_engine/application/services/inference/inference_service.py +17 -0
- inference_engine/application/services/inference/streaming_service.py +37 -0
- inference_engine/application/services/optimization/__init__.py +2 -0
- inference_engine/application/services/optimization/adaptive_tuner.py +26 -0
- inference_engine/application/services/routing/__init__.py +2 -0
- inference_engine/application/services/routing/routing_service.py +42 -0
- inference_engine/benchmarking/__init__.py +1 -0
- inference_engine/benchmarking/budget.py +42 -0
- inference_engine/benchmarking/change_gate.py +1127 -0
- inference_engine/benchmarking/context_store.py +164 -0
- inference_engine/benchmarking/decision_report.py +405 -0
- inference_engine/benchmarking/eval.py +343 -0
- inference_engine/benchmarking/evidence_completeness.py +454 -0
- inference_engine/benchmarking/evidence_manifest.py +255 -0
- inference_engine/benchmarking/experiment_provenance.py +514 -0
- inference_engine/benchmarking/export.py +321 -0
- inference_engine/benchmarking/harness.py +368 -0
- inference_engine/benchmarking/ifstruct_subset.py +60 -0
- inference_engine/benchmarking/ifstruct_validator.py +458 -0
- inference_engine/benchmarking/openrouter_billing.py +1112 -0
- inference_engine/benchmarking/openrouter_billing_run.py +1436 -0
- inference_engine/benchmarking/openrouter_evidence_semantics.py +330 -0
- inference_engine/benchmarking/paired_comparison.py +607 -0
- inference_engine/benchmarking/pilot_analysis.py +149 -0
- inference_engine/benchmarking/pilot_contract.py +516 -0
- inference_engine/benchmarking/pilot_decision.py +349 -0
- inference_engine/benchmarking/pilot_evidence_store.py +239 -0
- inference_engine/benchmarking/pilot_semantics.py +316 -0
- inference_engine/benchmarking/reconciliation.py +467 -0
- inference_engine/benchmarking/segmentation.py +332 -0
- inference_engine/benchmarking/sqlite_ledger.py +1306 -0
- inference_engine/benchmarking/statistics.py +394 -0
- inference_engine/cli.py +142 -0
- inference_engine/config.py +53 -0
- inference_engine/domain/__init__.py +2 -0
- inference_engine/domain/batching/__init__.py +2 -0
- inference_engine/domain/batching/adaptive.py +123 -0
- inference_engine/domain/batching/algorithms.py +108 -0
- inference_engine/domain/batching/base.py +19 -0
- inference_engine/domain/batching/priority.py +73 -0
- inference_engine/domain/batching/semantic.py +31 -0
- inference_engine/domain/caching/__init__.py +2 -0
- inference_engine/domain/caching/base.py +49 -0
- inference_engine/domain/caching/eviction.py +108 -0
- inference_engine/domain/caching/exact.py +97 -0
- inference_engine/domain/caching/prefix.py +73 -0
- inference_engine/domain/caching/semantic.py +47 -0
- inference_engine/domain/cost/__init__.py +2 -0
- inference_engine/domain/cost/attribution.py +75 -0
- inference_engine/domain/cost/calculator.py +43 -0
- inference_engine/domain/cost/optimization.py +96 -0
- inference_engine/domain/cost/pricing.py +240 -0
- inference_engine/domain/cost/routing_estimator.py +51 -0
- inference_engine/domain/models/__init__.py +42 -0
- inference_engine/domain/models/batch.py +84 -0
- inference_engine/domain/models/cache.py +138 -0
- inference_engine/domain/models/cost.py +83 -0
- inference_engine/domain/models/economics.py +222 -0
- inference_engine/domain/models/execution.py +145 -0
- inference_engine/domain/models/request.py +97 -0
- inference_engine/domain/models/response.py +77 -0
- inference_engine/domain/models/routing.py +123 -0
- inference_engine/domain/routing/__init__.py +2 -0
- inference_engine/domain/routing/base.py +15 -0
- inference_engine/domain/routing/baseline.py +148 -0
- inference_engine/domain/routing/capability.py +14 -0
- inference_engine/domain/routing/complexity.py +64 -0
- inference_engine/domain/routing/cost_aware.py +145 -0
- inference_engine/domain/routing/cost_estimator.py +23 -0
- inference_engine/domain/routing/load_balanced.py +56 -0
- inference_engine/domain/routing/policy.py +271 -0
- inference_engine/infrastructure/embeddings/embedding_cache.py +70 -0
- inference_engine/infrastructure/importers/__init__.py +1 -0
- inference_engine/infrastructure/importers/litellm.py +336 -0
- inference_engine/infrastructure/importers/litellm_exact.py +101 -0
- inference_engine/infrastructure/models/__init__.py +2 -0
- inference_engine/infrastructure/models/base.py +68 -0
- inference_engine/infrastructure/models/errors.py +133 -0
- inference_engine/infrastructure/models/model_pool.py +62 -0
- inference_engine/infrastructure/models/openai_backend.py +370 -0
- inference_engine/infrastructure/models/tgi_backend.py +113 -0
- inference_engine/infrastructure/models/vllm_backend.py +124 -0
- inference_engine/infrastructure/telemetry/__init__.py +1 -0
- inference_engine/infrastructure/telemetry/request_log.py +529 -0
- inference_engine/utils/__init__.py +1 -0
- inference_engine/utils/concurrency.py +18 -0
- inference_engine/utils/result.py +57 -0
- inference_engine/utils/similarity.py +13 -0
- inference_engine/utils/text_utils.py +7 -0
- inference_engine/utils/time.py +10 -0
- inferenceledger-0.1.0.dist-info/METADATA +181 -0
- inferenceledger-0.1.0.dist-info/RECORD +116 -0
- inferenceledger-0.1.0.dist-info/WHEEL +5 -0
- inferenceledger-0.1.0.dist-info/entry_points.txt +3 -0
- inferenceledger-0.1.0.dist-info/licenses/LICENSE +22 -0
- inferenceledger-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from fastapi import FastAPI
|
|
4
|
+
|
|
5
|
+
from .routes.inference import router as inference_router
|
|
6
|
+
|
|
7
|
+
app = FastAPI(
|
|
8
|
+
title="InferenceLedger Reference Executor",
|
|
9
|
+
version="0.1.0",
|
|
10
|
+
description=(
|
|
11
|
+
"Narrow OpenAI-compatible reference execution surface used for controlled "
|
|
12
|
+
"InferenceLedger experiments. It is not the product control plane."
|
|
13
|
+
),
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
app.include_router(inference_router, prefix="/v1")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@app.get("/health")
|
|
20
|
+
async def health() -> dict[str, str]:
|
|
21
|
+
return {"status": "ok", "component": "reference-executor"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@app.get("/health/ready")
|
|
25
|
+
async def ready() -> dict[str, bool]:
|
|
26
|
+
return {"ready": True}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@app.get("/health/live")
|
|
30
|
+
async def live() -> dict[str, bool]:
|
|
31
|
+
return {"alive": True}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, HTTPException, status
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
from ....domain.models.request import InferenceRequest, ModelParameters
|
|
9
|
+
from ....infrastructure.models.errors import ProviderError, ProviderErrorType
|
|
10
|
+
from ....infrastructure.models.openai_backend import OpenAIBackend, RetryPolicy
|
|
11
|
+
|
|
12
|
+
router = APIRouter()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class InferenceRequestBody(BaseModel):
|
|
16
|
+
prompt: str = Field(min_length=1)
|
|
17
|
+
model: str = "gpt-4o-mini"
|
|
18
|
+
max_tokens: int = Field(default=128, ge=1)
|
|
19
|
+
temperature: float = Field(default=0.0, ge=0.0, le=2.0)
|
|
20
|
+
top_p: float = Field(default=0.9, ge=0.0, le=1.0)
|
|
21
|
+
timeout_seconds: float = Field(default=30.0, gt=0.0)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class InferenceResponseBody(BaseModel):
|
|
25
|
+
text: str
|
|
26
|
+
model_used: str
|
|
27
|
+
finish_reason: str
|
|
28
|
+
latency_ms: int
|
|
29
|
+
prompt_tokens: int
|
|
30
|
+
completion_tokens: int
|
|
31
|
+
total_tokens: int
|
|
32
|
+
cached_tokens: int
|
|
33
|
+
final_attempt_cost_usd: float | None
|
|
34
|
+
provider_attempt_count: int
|
|
35
|
+
provider_retry_count: int
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@router.post("/inference", response_model=InferenceResponseBody)
|
|
39
|
+
async def create_inference(payload: InferenceRequestBody) -> InferenceResponseBody:
|
|
40
|
+
api_key = os.getenv("OPENAI_API_KEY")
|
|
41
|
+
if not api_key:
|
|
42
|
+
raise HTTPException(
|
|
43
|
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
44
|
+
detail="OPENAI_API_KEY is required for real provider inference.",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
backend = OpenAIBackend(
|
|
49
|
+
api_key=api_key,
|
|
50
|
+
model_name=payload.model,
|
|
51
|
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
|
52
|
+
timeout_seconds=payload.timeout_seconds,
|
|
53
|
+
retry_policy=RetryPolicy(max_attempts=2),
|
|
54
|
+
)
|
|
55
|
+
response = await backend.infer(
|
|
56
|
+
InferenceRequest(
|
|
57
|
+
prompt=payload.prompt,
|
|
58
|
+
parameters=ModelParameters(
|
|
59
|
+
max_tokens=payload.max_tokens,
|
|
60
|
+
temperature=payload.temperature,
|
|
61
|
+
top_p=payload.top_p,
|
|
62
|
+
),
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
except ImportError as exc:
|
|
66
|
+
raise HTTPException(
|
|
67
|
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
68
|
+
detail="OpenAI provider dependency is not installed.",
|
|
69
|
+
) from exc
|
|
70
|
+
except ProviderError as exc:
|
|
71
|
+
raise HTTPException(
|
|
72
|
+
status_code=_provider_error_status(exc),
|
|
73
|
+
detail={
|
|
74
|
+
"type": exc.error_type.value,
|
|
75
|
+
"message": exc.message,
|
|
76
|
+
"retryable": exc.retryable,
|
|
77
|
+
"provider_attempt_count": exc.provider_attempt_count,
|
|
78
|
+
"provider_retry_count": exc.provider_retry_count,
|
|
79
|
+
},
|
|
80
|
+
) from exc
|
|
81
|
+
|
|
82
|
+
return InferenceResponseBody(
|
|
83
|
+
text=response.text,
|
|
84
|
+
model_used=response.model_used,
|
|
85
|
+
finish_reason=response.finish_reason,
|
|
86
|
+
latency_ms=response.latency_ms,
|
|
87
|
+
prompt_tokens=response.usage.prompt_tokens,
|
|
88
|
+
completion_tokens=response.usage.completion_tokens,
|
|
89
|
+
total_tokens=response.usage.total_tokens,
|
|
90
|
+
cached_tokens=response.usage.cached_tokens,
|
|
91
|
+
final_attempt_cost_usd=response.usage.cost_usd,
|
|
92
|
+
provider_attempt_count=response.provider_attempt_count,
|
|
93
|
+
provider_retry_count=response.provider_retry_count,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _provider_error_status(error: ProviderError) -> int:
|
|
98
|
+
return {
|
|
99
|
+
ProviderErrorType.AUTHENTICATION: status.HTTP_502_BAD_GATEWAY,
|
|
100
|
+
ProviderErrorType.INVALID_REQUEST: status.HTTP_400_BAD_REQUEST,
|
|
101
|
+
ProviderErrorType.MISSING_USAGE: status.HTTP_502_BAD_GATEWAY,
|
|
102
|
+
ProviderErrorType.RATE_LIMIT: status.HTTP_429_TOO_MANY_REQUESTS,
|
|
103
|
+
ProviderErrorType.SERVER_ERROR: status.HTTP_502_BAD_GATEWAY,
|
|
104
|
+
ProviderErrorType.TIMEOUT: status.HTTP_504_GATEWAY_TIMEOUT,
|
|
105
|
+
ProviderErrorType.UNKNOWN: status.HTTP_502_BAD_GATEWAY,
|
|
106
|
+
}[error.error_type]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from .inference_dto import InferenceInputDTO, InferenceOutputDTO
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class BatchInputDTO:
|
|
10
|
+
requests: list[InferenceInputDTO]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class BatchOutputDTO:
|
|
15
|
+
responses: list[InferenceOutputDTO]
|
|
16
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class InferenceInputDTO:
|
|
8
|
+
prompt: str
|
|
9
|
+
max_tokens: int = 1024
|
|
10
|
+
temperature: float = 0.7
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class InferenceOutputDTO:
|
|
15
|
+
text: str
|
|
16
|
+
model_used: str
|
|
17
|
+
tokens_used: int
|
|
18
|
+
cost_usd: float
|
|
19
|
+
latency_ms: int
|
|
20
|
+
cache_hit: bool
|
|
21
|
+
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Application services for the authoritative migration-evidence path."""
|
|
2
|
+
|
|
3
|
+
from .litellm_arm_service import (
|
|
4
|
+
LiteLLMArmExecutionRequest,
|
|
5
|
+
LiteLLMArmExecutionResult,
|
|
6
|
+
execute_litellm_arm,
|
|
7
|
+
)
|
|
8
|
+
from .migration_decision_service import (
|
|
9
|
+
MigrationDecisionRequest,
|
|
10
|
+
MigrationDecisionResult,
|
|
11
|
+
decide_stored_change,
|
|
12
|
+
)
|
|
13
|
+
from .run_evidence_service import PersistedBenchmarkRun, persist_benchmark_run
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"LiteLLMArmExecutionRequest",
|
|
17
|
+
"LiteLLMArmExecutionResult",
|
|
18
|
+
"MigrationDecisionRequest",
|
|
19
|
+
"MigrationDecisionResult",
|
|
20
|
+
"PersistedBenchmarkRun",
|
|
21
|
+
"decide_stored_change",
|
|
22
|
+
"execute_litellm_arm",
|
|
23
|
+
"persist_benchmark_run",
|
|
24
|
+
]
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
import importlib
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from dataclasses import dataclass, replace
|
|
8
|
+
from hashlib import sha256
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Protocol
|
|
11
|
+
|
|
12
|
+
from ....benchmarking.eval import evaluate_text
|
|
13
|
+
from ....benchmarking.experiment_provenance import (
|
|
14
|
+
ExperimentProvenanceError,
|
|
15
|
+
build_execution_provenance,
|
|
16
|
+
execution_interval_from_standard_logging_payloads,
|
|
17
|
+
require_committed_clean_experiment_spec,
|
|
18
|
+
)
|
|
19
|
+
from ....benchmarking.harness import load_workload
|
|
20
|
+
from ....benchmarking.pilot_contract import PilotInstanceContract, load_optional_pilot_contract
|
|
21
|
+
from ....benchmarking.segmentation import BenchmarkRequestContext
|
|
22
|
+
from ....domain.models.economics import ExactRequestCostEvidence
|
|
23
|
+
from ....infrastructure.importers.litellm import (
|
|
24
|
+
import_litellm_standard_logging_chain,
|
|
25
|
+
sanitize_standard_logging_payload,
|
|
26
|
+
)
|
|
27
|
+
from ....infrastructure.importers.litellm_exact import extract_litellm_exact_cost_evidence
|
|
28
|
+
from ....infrastructure.telemetry.request_log import JsonlRequestLog, RequestTrace
|
|
29
|
+
from .run_evidence_service import persist_benchmark_run
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _PayloadCapture(Protocol):
|
|
33
|
+
payloads: list[dict[str, object]]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class LiteLLMArmExecutionRequest:
|
|
38
|
+
"""Inputs for the selected external execution/import adapter."""
|
|
39
|
+
|
|
40
|
+
experiment_path: Path
|
|
41
|
+
arm: str
|
|
42
|
+
sqlite_ledger_path: Path
|
|
43
|
+
output_dir: Path
|
|
44
|
+
raw_dir: Path
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class LiteLLMArmExecutionResult:
|
|
49
|
+
exit_code: int
|
|
50
|
+
message: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def execute_litellm_arm(request: LiteLLMArmExecutionRequest) -> LiteLLMArmExecutionResult:
|
|
54
|
+
"""Execute one pre-registered LiteLLM arm and cross the canonical run-evidence boundary."""
|
|
55
|
+
if request.arm not in {"baseline", "candidate"}:
|
|
56
|
+
raise ValueError("arm must be baseline or candidate")
|
|
57
|
+
|
|
58
|
+
experiment_path = request.experiment_path
|
|
59
|
+
try:
|
|
60
|
+
snapshot = require_committed_clean_experiment_spec(experiment_path)
|
|
61
|
+
except ExperimentProvenanceError as exc:
|
|
62
|
+
raise SystemExit(f"experiment spec provenance: {exc}") from exc
|
|
63
|
+
|
|
64
|
+
experiment = _load_json_object(experiment_path)
|
|
65
|
+
pilot_contract = load_optional_pilot_contract(experiment)
|
|
66
|
+
workload_path = Path(str(experiment["workload"]["path"]))
|
|
67
|
+
expected_sha = str(experiment["workload"]["sha256"])
|
|
68
|
+
actual_sha = sha256(workload_path.read_bytes()).hexdigest()
|
|
69
|
+
if actual_sha != expected_sha:
|
|
70
|
+
raise ValueError(
|
|
71
|
+
"workload SHA-256 does not match the pre-registered experiment; "
|
|
72
|
+
f"expected={expected_sha}, actual={actual_sha}"
|
|
73
|
+
)
|
|
74
|
+
_validate_pilot_workload_identity(
|
|
75
|
+
contract=pilot_contract,
|
|
76
|
+
workload_sha256=actual_sha,
|
|
77
|
+
workload_item_count=len(load_workload(workload_path)),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
arm = request.arm
|
|
81
|
+
arm_spec = experiment[arm]
|
|
82
|
+
run_id = str(arm_spec["run_id"])
|
|
83
|
+
runtime_intent = experiment["runtime_intent"]
|
|
84
|
+
model = str(runtime_intent["model_argument"])
|
|
85
|
+
api_base = str(runtime_intent["endpoint"])
|
|
86
|
+
generation = _generation_settings(experiment)
|
|
87
|
+
quality_limitation = _quality_limitation(experiment)
|
|
88
|
+
workload = load_workload(workload_path)
|
|
89
|
+
output_dir = request.output_dir
|
|
90
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
raw_dir = request.raw_dir / run_id
|
|
92
|
+
raw_dir.mkdir(parents=True, exist_ok=True)
|
|
93
|
+
|
|
94
|
+
ledger_path = output_dir / f"{run_id}.jsonl"
|
|
95
|
+
request_log = JsonlRequestLog(ledger_path)
|
|
96
|
+
litellm, capture_logger = _load_litellm()
|
|
97
|
+
capture: _PayloadCapture = capture_logger()
|
|
98
|
+
litellm.logging_callback_manager.add_litellm_success_callback(capture)
|
|
99
|
+
litellm.logging_callback_manager.add_litellm_failure_callback(capture)
|
|
100
|
+
|
|
101
|
+
traces: list[RequestTrace] = []
|
|
102
|
+
request_contexts: list[BenchmarkRequestContext] = []
|
|
103
|
+
exact_costs: list[ExactRequestCostEvidence] = []
|
|
104
|
+
sanitized_payloads: list[dict[str, object]] = []
|
|
105
|
+
raw_hashes: list[dict[str, object]] = []
|
|
106
|
+
|
|
107
|
+
for item in workload:
|
|
108
|
+
capture.payloads.clear()
|
|
109
|
+
kwargs = _completion_kwargs(
|
|
110
|
+
model=model,
|
|
111
|
+
api_base=api_base,
|
|
112
|
+
prompt=item.prompt,
|
|
113
|
+
generation=generation,
|
|
114
|
+
arm=arm,
|
|
115
|
+
arm_spec=arm_spec if isinstance(arm_spec, dict) else {},
|
|
116
|
+
)
|
|
117
|
+
response_text = ""
|
|
118
|
+
try:
|
|
119
|
+
response = litellm.completion(**kwargs)
|
|
120
|
+
response_text = _completion_text(response)
|
|
121
|
+
except Exception:
|
|
122
|
+
response_text = ""
|
|
123
|
+
|
|
124
|
+
payload_chain = _wait_for_payload_chain(capture, workload_item_id=item.id)
|
|
125
|
+
trace = import_litellm_standard_logging_chain(payload_chain)
|
|
126
|
+
if pilot_contract is not None:
|
|
127
|
+
exact_costs.append(
|
|
128
|
+
extract_litellm_exact_cost_evidence(
|
|
129
|
+
payload_chain,
|
|
130
|
+
currency=pilot_contract.economic.currency,
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
raw_path = raw_dir / f"{item.id}.json"
|
|
135
|
+
raw_bytes = json.dumps(
|
|
136
|
+
list(payload_chain), indent=2, sort_keys=True, default=str
|
|
137
|
+
).encode("utf-8")
|
|
138
|
+
raw_path.write_bytes(raw_bytes)
|
|
139
|
+
raw_hashes.append(
|
|
140
|
+
{
|
|
141
|
+
"workload_item_id": item.id,
|
|
142
|
+
"logical_path": f"private_raw/{run_id}/{item.id}.json",
|
|
143
|
+
"sha256": sha256(raw_bytes).hexdigest(),
|
|
144
|
+
"byte_size": len(raw_bytes),
|
|
145
|
+
"attempt_count": len(payload_chain),
|
|
146
|
+
}
|
|
147
|
+
)
|
|
148
|
+
sanitized_payloads.extend(
|
|
149
|
+
sanitize_standard_logging_payload(payload) for payload in payload_chain
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
eval_result = evaluate_text(response_text, item.eval_spec)
|
|
153
|
+
if eval_result is not None and trace.error_type is None:
|
|
154
|
+
trace = replace(
|
|
155
|
+
trace,
|
|
156
|
+
quality_passed=eval_result.passed,
|
|
157
|
+
quality_score=eval_result.score,
|
|
158
|
+
quality_reason=eval_result.reason,
|
|
159
|
+
eval_type=eval_result.eval_type,
|
|
160
|
+
)
|
|
161
|
+
request_log.append(trace)
|
|
162
|
+
traces.append(trace)
|
|
163
|
+
request_contexts.append(
|
|
164
|
+
BenchmarkRequestContext.from_tags(
|
|
165
|
+
request_id=trace.request_id,
|
|
166
|
+
workload_item_id=item.id,
|
|
167
|
+
tags=item.tags,
|
|
168
|
+
)
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
provider = traces[0].provider if traces else "unknown"
|
|
172
|
+
model_name = traces[0].model if traces else "unknown"
|
|
173
|
+
report_path = output_dir / f"{run_id}.report.json"
|
|
174
|
+
segment_path = output_dir / f"{run_id}.segments.json"
|
|
175
|
+
persisted = persist_benchmark_run(
|
|
176
|
+
run_id=run_id,
|
|
177
|
+
workload_path=workload_path,
|
|
178
|
+
strategy=f"litellm_{arm}",
|
|
179
|
+
provider=provider,
|
|
180
|
+
model=model_name,
|
|
181
|
+
ledger_path=ledger_path,
|
|
182
|
+
sqlite_ledger_path=request.sqlite_ledger_path,
|
|
183
|
+
traces=traces,
|
|
184
|
+
request_contexts=request_contexts,
|
|
185
|
+
route_traces=(),
|
|
186
|
+
report_path=report_path,
|
|
187
|
+
segment_report_path=segment_path,
|
|
188
|
+
additional_limitations=(
|
|
189
|
+
"No InferenceLedger route decision was executed; reconciliation is expected to be MISSING_ROUTE.",
|
|
190
|
+
quality_limitation,
|
|
191
|
+
),
|
|
192
|
+
pilot_acquisition=(
|
|
193
|
+
pilot_contract.acquisition_for_arm(arm) if pilot_contract is not None else None
|
|
194
|
+
),
|
|
195
|
+
exact_cost_evidence=exact_costs,
|
|
196
|
+
)
|
|
197
|
+
report = persisted.report
|
|
198
|
+
|
|
199
|
+
sanitized_path = output_dir / f"{run_id}.sanitized-payloads.jsonl"
|
|
200
|
+
with sanitized_path.open("w", encoding="utf-8") as handle:
|
|
201
|
+
for payload in sanitized_payloads:
|
|
202
|
+
handle.write(json.dumps(payload, sort_keys=True) + "\n")
|
|
203
|
+
hashes_path = output_dir / f"{run_id}.raw-payload-sha256.json"
|
|
204
|
+
hashes_path.write_text(
|
|
205
|
+
json.dumps(raw_hashes, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
interval = execution_interval_from_standard_logging_payloads(sanitized_payloads)
|
|
209
|
+
try:
|
|
210
|
+
provenance = build_execution_provenance(
|
|
211
|
+
snapshot=snapshot,
|
|
212
|
+
interval=interval,
|
|
213
|
+
workload_sha256=actual_sha,
|
|
214
|
+
declared_status=str(experiment["status"]) if experiment.get("status") is not None else None,
|
|
215
|
+
declared_locked_at_utc=(
|
|
216
|
+
str(experiment["locked_at_utc"])
|
|
217
|
+
if experiment.get("locked_at_utc") is not None
|
|
218
|
+
else None
|
|
219
|
+
),
|
|
220
|
+
require_spec_precedes_execution=True,
|
|
221
|
+
)
|
|
222
|
+
except ExperimentProvenanceError as exc:
|
|
223
|
+
raise SystemExit(f"experiment spec provenance: {exc}") from exc
|
|
224
|
+
provenance_path = output_dir / f"{run_id}.provenance.json"
|
|
225
|
+
provenance_path.write_text(
|
|
226
|
+
json.dumps(provenance, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
message = " ".join(
|
|
230
|
+
[
|
|
231
|
+
f"run_id={run_id}",
|
|
232
|
+
f"arm={arm}",
|
|
233
|
+
f"requests={report.request_count}",
|
|
234
|
+
f"successes={report.success_count}",
|
|
235
|
+
f"failures={report.failure_count}",
|
|
236
|
+
f"attempts={report.provider_attempt_count}",
|
|
237
|
+
f"retries={report.provider_retry_count}",
|
|
238
|
+
f"quality_pass_rate={report.quality_pass_rate}",
|
|
239
|
+
f"raw_dir={raw_dir}",
|
|
240
|
+
f"report_path={report_path}",
|
|
241
|
+
]
|
|
242
|
+
)
|
|
243
|
+
return LiteLLMArmExecutionResult(exit_code=0, message=message)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _validate_pilot_workload_identity(
|
|
247
|
+
*,
|
|
248
|
+
contract: PilotInstanceContract | None,
|
|
249
|
+
workload_sha256: str,
|
|
250
|
+
workload_item_count: int,
|
|
251
|
+
) -> None:
|
|
252
|
+
if contract is None:
|
|
253
|
+
return
|
|
254
|
+
if contract.workload.sha256 != workload_sha256:
|
|
255
|
+
raise ValueError("pilot contract workload SHA-256 disagrees with experiment workload")
|
|
256
|
+
if contract.workload.item_count != workload_item_count:
|
|
257
|
+
raise ValueError("pilot contract workload item_count disagrees with frozen workload")
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _generation_settings(experiment: dict[str, Any]) -> dict[str, Any]:
|
|
261
|
+
generation = experiment.get("generation")
|
|
262
|
+
if not isinstance(generation, dict):
|
|
263
|
+
raise ValueError("experiment.generation is required")
|
|
264
|
+
temperature = generation.get("temperature")
|
|
265
|
+
max_tokens = generation.get("max_tokens")
|
|
266
|
+
stream = generation.get("stream", False)
|
|
267
|
+
if not isinstance(temperature, (int, float)) or isinstance(temperature, bool):
|
|
268
|
+
raise ValueError("experiment.generation.temperature must be numeric")
|
|
269
|
+
if not isinstance(max_tokens, int) or isinstance(max_tokens, bool) or max_tokens < 1:
|
|
270
|
+
raise ValueError("experiment.generation.max_tokens must be a positive int")
|
|
271
|
+
if not isinstance(stream, bool):
|
|
272
|
+
raise ValueError("experiment.generation.stream must be a boolean")
|
|
273
|
+
if stream:
|
|
274
|
+
raise ValueError("streaming executions are not supported by this runner")
|
|
275
|
+
return {"temperature": float(temperature), "max_tokens": max_tokens, "stream": False}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _quality_limitation(experiment: dict[str, Any]) -> str:
|
|
279
|
+
evaluator = experiment.get("quality_evaluator")
|
|
280
|
+
if isinstance(evaluator, dict) and isinstance(evaluator.get("measures"), str):
|
|
281
|
+
return f"Quality scoring is deterministic: {evaluator['measures']}"
|
|
282
|
+
return "Quality scoring is deterministic workload-declared evaluation, not semantic quality."
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _completion_kwargs(
|
|
286
|
+
*,
|
|
287
|
+
model: str,
|
|
288
|
+
api_base: str,
|
|
289
|
+
prompt: str,
|
|
290
|
+
generation: dict[str, Any],
|
|
291
|
+
arm: str,
|
|
292
|
+
arm_spec: dict[str, Any],
|
|
293
|
+
) -> dict[str, Any]:
|
|
294
|
+
kwargs: dict[str, Any] = {
|
|
295
|
+
"model": model,
|
|
296
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
297
|
+
"api_base": api_base,
|
|
298
|
+
"temperature": generation["temperature"],
|
|
299
|
+
"max_tokens": generation["max_tokens"],
|
|
300
|
+
"stream": False,
|
|
301
|
+
}
|
|
302
|
+
if arm == "candidate":
|
|
303
|
+
response_format = arm_spec.get("response_format")
|
|
304
|
+
if not isinstance(response_format, dict):
|
|
305
|
+
raise ValueError("candidate.response_format is required for the candidate arm")
|
|
306
|
+
kwargs["response_format"] = response_format
|
|
307
|
+
return kwargs
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _load_litellm() -> tuple[Any, Any]:
|
|
311
|
+
try:
|
|
312
|
+
litellm = importlib.import_module("litellm")
|
|
313
|
+
except ImportError as exc:
|
|
314
|
+
raise SystemExit(
|
|
315
|
+
"LiteLLM is not installed in this interpreter. Use the isolated Mission 4 "
|
|
316
|
+
"environment; do not add LiteLLM to repository dependencies."
|
|
317
|
+
) from exc
|
|
318
|
+
|
|
319
|
+
class StandardLogCapture:
|
|
320
|
+
def __init__(self) -> None:
|
|
321
|
+
self.payloads: list[dict[str, object]] = []
|
|
322
|
+
|
|
323
|
+
def __call__(self, kwargs: dict[str, Any], *_args: object, **_kwargs: object) -> None:
|
|
324
|
+
payload = kwargs.get("standard_logging_object")
|
|
325
|
+
if payload is None:
|
|
326
|
+
return
|
|
327
|
+
self.payloads.append(_payload_dict(payload))
|
|
328
|
+
|
|
329
|
+
return litellm, StandardLogCapture
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _wait_for_payload_chain(
|
|
333
|
+
capture: _PayloadCapture,
|
|
334
|
+
*,
|
|
335
|
+
workload_item_id: str,
|
|
336
|
+
timeout_seconds: float = 15.0,
|
|
337
|
+
settle_seconds: float = 0.5,
|
|
338
|
+
) -> tuple[dict[str, object], ...]:
|
|
339
|
+
"""Collect the complete LiteLLM callback chain after it becomes quiescent.
|
|
340
|
+
|
|
341
|
+
LiteLLM submits logging callbacks asynchronously. Multiple payloads are valid and represent the
|
|
342
|
+
retry/fallback attempt chain; they must not be rejected merely because more than one provider
|
|
343
|
+
invocation occurred.
|
|
344
|
+
"""
|
|
345
|
+
deadline = time.monotonic() + timeout_seconds
|
|
346
|
+
last_count = 0
|
|
347
|
+
last_change = time.monotonic()
|
|
348
|
+
while time.monotonic() < deadline:
|
|
349
|
+
count = len(capture.payloads)
|
|
350
|
+
now = time.monotonic()
|
|
351
|
+
if count != last_count:
|
|
352
|
+
last_count = count
|
|
353
|
+
last_change = now
|
|
354
|
+
if count > 0 and now - last_change >= settle_seconds:
|
|
355
|
+
return tuple(copy.deepcopy(capture.payloads))
|
|
356
|
+
time.sleep(0.05)
|
|
357
|
+
raise RuntimeError(
|
|
358
|
+
f"{workload_item_id}: LiteLLM emitted no settled StandardLoggingPayload chain "
|
|
359
|
+
f"within {timeout_seconds:.1f}s"
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _wait_for_single_payload(
|
|
364
|
+
capture: _PayloadCapture,
|
|
365
|
+
*,
|
|
366
|
+
workload_item_id: str,
|
|
367
|
+
timeout_seconds: float = 15.0,
|
|
368
|
+
) -> dict[str, object]:
|
|
369
|
+
"""Compatibility helper retained for historical unit imports; rejects multi-attempt chains."""
|
|
370
|
+
payloads = _wait_for_payload_chain(
|
|
371
|
+
capture,
|
|
372
|
+
workload_item_id=workload_item_id,
|
|
373
|
+
timeout_seconds=timeout_seconds,
|
|
374
|
+
)
|
|
375
|
+
if len(payloads) != 1:
|
|
376
|
+
raise RuntimeError(
|
|
377
|
+
f"{workload_item_id}: expected exactly one LiteLLM StandardLoggingPayload, "
|
|
378
|
+
f"observed={len(payloads)}"
|
|
379
|
+
)
|
|
380
|
+
return payloads[0]
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _payload_dict(payload: object) -> dict[str, object]:
|
|
384
|
+
if hasattr(payload, "model_dump"):
|
|
385
|
+
dumped = payload.model_dump()
|
|
386
|
+
if isinstance(dumped, dict):
|
|
387
|
+
return {str(key): copy.deepcopy(value) for key, value in dumped.items()}
|
|
388
|
+
if isinstance(payload, dict):
|
|
389
|
+
return {str(key): copy.deepcopy(value) for key, value in payload.items()}
|
|
390
|
+
raise TypeError(f"LiteLLM standard_logging_object has unsupported type {type(payload)!r}")
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _completion_text(response: object) -> str:
|
|
394
|
+
choices = getattr(response, "choices", None)
|
|
395
|
+
if not choices:
|
|
396
|
+
return ""
|
|
397
|
+
message = getattr(choices[0], "message", None)
|
|
398
|
+
content = getattr(message, "content", None)
|
|
399
|
+
return content if isinstance(content, str) else ""
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _load_json_object(path: Path) -> dict[str, Any]:
|
|
403
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
404
|
+
if not isinstance(raw, dict):
|
|
405
|
+
raise ValueError(f"{path} must contain a JSON object")
|
|
406
|
+
return raw
|