Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 102 additions & 11 deletions src/inferrsi/apps/workflows/indexer_evolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import os
import urllib.parse
import urllib.request
import uuid
from collections.abc import Callable, Mapping, Sequence
from pathlib import Path

Expand Down Expand Up @@ -242,6 +241,70 @@ def http_error_302(self, req, fp, code, msg, headers):
http_error_301 = http_error_303 = http_error_307 = http_error_308 = http_error_302


_MAX_PROPOSAL_JSON_DEPTH = 128


def _reject_nonfinite_json(token: str) -> None:
raise ValueError(f"Non-finite JSON constant in proposal: {token}")


def _parse_finite_float(token: str) -> float:
value = float(token)
if not math.isfinite(value):
raise ValueError(f"Non-finite JSON float in proposal: {token}")
return value


def _check_json_depth(value: object) -> None:
stack: list[tuple[object, int]] = [(value, 0)]
while stack:
current, depth = stack.pop()
if depth > _MAX_PROPOSAL_JSON_DEPTH:
raise ValueError(
f"Proposal exceeds maximum JSON nesting depth ({_MAX_PROPOSAL_JSON_DEPTH})"
)
if isinstance(current, Mapping):
for item in current.values():
if isinstance(item, (Mapping, list, tuple)):
stack.append((item, depth + 1))
elif isinstance(current, (list, tuple)):
for item in current:
if isinstance(item, (Mapping, list, tuple)):
stack.append((item, depth + 1))


def _valid_session_id(raw_id: object) -> str | None:
if not isinstance(raw_id, str):
return None
candidate = raw_id.strip()
if not candidate or len(candidate) > 16384:
return None
try:
candidate.encode("utf-8")
except UnicodeEncodeError:
return None
return candidate


def _valid_usage(raw_usage: object) -> dict[str, int] | None:
if not isinstance(raw_usage, dict):
return None
prompt_tokens = raw_usage.get("prompt_tokens")
completion_tokens = raw_usage.get("completion_tokens")
if (
type(prompt_tokens) is not int
or type(completion_tokens) is not int
or prompt_tokens < 0
or completion_tokens < 0
):
return None
if "total_tokens" in raw_usage:
total_tokens = raw_usage["total_tokens"]
if type(total_tokens) is not int or total_tokens < 0:
return None
return {"input_tokens": prompt_tokens, "output_tokens": completion_tokens}


def _open_provider_request(
request: urllib.request.Request, *, timeout: float, direct_only: bool = False,
):
Expand Down Expand Up @@ -361,23 +424,51 @@ def _submit(job_id: str, handoff: Mapping, delivery_receipt: Mapping) -> Mapping
request, timeout=timeout_seconds, direct_only=direct_only,
) as response:
raw = json.loads(response.read().decode("utf-8"))
choice = raw["choices"][0]["message"]["content"]
proposal = json.loads(choice)
if not isinstance(raw, dict):
raise ValueError("Provider response body must be a JSON object")
session_id = _valid_session_id(raw.get("id"))
if session_id is None:
raise ValueError("Provider response requires a confirmed id")
raw_usage = raw.get("usage")
usage = None
if isinstance(raw_usage, dict):
prompt_tokens = raw_usage.get("prompt_tokens")
completion_tokens = raw_usage.get("completion_tokens")
if type(prompt_tokens) is int and type(completion_tokens) is int:
usage = {"input_tokens": prompt_tokens, "output_tokens": completion_tokens}
session_id = str(raw.get("id") or f"llm-{uuid.uuid4().hex[:12]}")
if raw_usage is None:
usage = None
else:
usage = _valid_usage(raw_usage)
if usage is None:
raise ValueError("Provider response usage must contain nonnegative integer tokens")
proposal = None
native_receipt: dict[str, object] = {
"job_id": job_id,
"response_id": session_id,
"model": model,
}
try:
choice = raw["choices"][0]["message"]["content"]
if not isinstance(choice, str):
raise TypeError("Completion message content must be a JSON string")
parsed_proposal = json.loads(
choice,
parse_float=_parse_finite_float,
parse_constant=_reject_nonfinite_json,
)
_check_json_depth(parsed_proposal)
if not isinstance(parsed_proposal, dict):
raise TypeError("Proposal JSON must be an object")
json.dumps(parsed_proposal, ensure_ascii=False, allow_nan=False).encode("utf-8")
proposal = parsed_proposal
except (KeyError, IndexError, TypeError, ValueError, RecursionError) as exc:
if usage is None:
raise ValueError(
"Provider response with malformed proposal requires confirmed integer usage"
) from exc
native_receipt["proposal_parse_error"] = type(exc).__name__
return {
"job_id": job_id,
"host": "openai_compatible",
"session_id": session_id,
"state": "completed",
"creation_receipt": {"job_id": job_id, "response_id": session_id, "model": model},
"native_receipt": {"job_id": job_id, "response_id": session_id, "model": model},
"native_receipt": native_receipt,
"usage": usage,
"budget_units_used": fixed_units,
"proposal": proposal,
Expand Down
Loading
Loading