"""Pure orchestration: progression -> composition -> instruction. The wrapper does not run or load any models. It makes HTTP calls to the three existing Hugging Face Spaces and returns one final activity. """ import asyncio import logging import time from typing import Any from urllib.parse import urlparse, urlunparse import httpx from pydantic import ValidationError from app.config import Settings from app.models import Activity, ActivityRequest, ActivityResponse logger = logging.getLogger("activity_generation") class PipelineError(Exception): def __init__(self, stage: str, code: str, message: str, status_code: int = 502): self.stage = stage self.code = code self.message = message self.status_code = status_code super().__init__(f"{stage}: {message}") def public_detail(self) -> dict[str, str]: return {"stage": self.stage, "code": self.code, "message": self.message} class StageClient: """Resolve a Space's POST path from its OpenAPI document, then reuse it. Override discovery by setting the service URL to its full POST path. """ def __init__(self, name: str, url: str, client: httpx.AsyncClient, attempts: int): self.name = name self.url = url.rstrip("/") self.client = client self.attempts = attempts self._endpoint: str | None = None self._endpoint_lock = asyncio.Lock() async def endpoint(self) -> str: if self._endpoint is not None: return self._endpoint async with self._endpoint_lock: if self._endpoint is not None: return self._endpoint parsed = urlparse(self.url) # An explicit path is a complete POST endpoint, not a docs page. if parsed.path not in ("", "/"): self._endpoint = self.url return self._endpoint openapi_url = urlunparse(parsed._replace(path="/openapi.json", query="", fragment="")) try: response = await self.client.get(openapi_url) response.raise_for_status() spec = response.json() except (httpx.HTTPError, ValueError) as exc: logger.warning("Could not discover %s POST endpoint: %s", self.name, type(exc).__name__) raise PipelineError( self.name, "endpoint_discovery_failed", f"Could not read this Space's OpenAPI schema. Set {self.name.upper()}_API_URL to its full POST endpoint.", ) from exc paths = spec.get("paths", {}) if isinstance(spec, dict) else {} operations = [ (path, details["post"]) for path, details in paths.items() if isinstance(details, dict) and isinstance(details.get("post"), dict) ] if isinstance(paths, dict) else [] if not operations: raise PipelineError(self.name, "endpoint_discovery_failed", "No POST endpoint found in the Space OpenAPI schema.") if len(operations) == 1: path = operations[0][0] else: # Prefer generation endpoints, then paths related to this particular stage. matches = [p for p, op in operations if any(word in (p + ' ' + str(op.get('operationId', ''))).lower() for word in ('generat', self.name, 'predict', 'compos', 'instruct'))] if len(matches) != 1: raise PipelineError( self.name, "ambiguous_endpoint", f"Found {len(operations)} POST routes. Set {self.name.upper()}_API_URL to the exact path listed in /docs.", ) path = matches[0] self._endpoint = self.url + (path if path.startswith("/") else "/" + path) logger.info("Discovered %s API POST path: %s", self.name, path) return self._endpoint async def post(self, body: dict[str, Any]) -> dict[str, Any]: endpoint = await self.endpoint() for attempt in range(self.attempts): started = time.monotonic() try: response = await self.client.post(endpoint, json=body) if response.status_code in {429, 502, 503, 504} and attempt + 1 < self.attempts: logger.warning("stage=%s status=%s retry=%s", self.name, response.status_code, attempt + 1) await asyncio.sleep(2 ** attempt) continue if response.is_error: logger.warning("stage=%s http_status=%d", self.name, response.status_code) raise PipelineError( self.name, "upstream_http_error", f"Upstream {self.name} API returned HTTP {response.status_code}. Check its POST request contract and Space logs.", 503 if response.status_code in (429, 503) else 502, ) try: payload = response.json() except ValueError as exc: raise PipelineError(self.name, "invalid_json", "Upstream API did not return valid JSON.") from exc if not isinstance(payload, dict): raise PipelineError(self.name, "invalid_output", "Upstream API must return a JSON object.") logger.info("stage=%s elapsed_seconds=%.2f status=ok", self.name, time.monotonic() - started) return payload except httpx.TimeoutException as exc: if attempt + 1 < self.attempts: logger.warning("stage=%s timeout retry=%s", self.name, attempt + 1) await asyncio.sleep(2 ** attempt) continue raise PipelineError(self.name, "upstream_timeout", "The model API timed out.", 504) from exc except httpx.RequestError as exc: if attempt + 1 < self.attempts: logger.warning("stage=%s connection_error retry=%s", self.name, attempt + 1) await asyncio.sleep(2 ** attempt) continue raise PipelineError(self.name, "upstream_unavailable", "Could not connect to the model API.", 502) from exc raise AssertionError("unreachable") def unwrap_object(payload: dict[str, Any], stage: str, *, envelope: str | None = None) -> dict[str, Any]: """Unwrap the common `output` envelope and optional `progression` key. Progression API is allowed to add/remove progression fields. The wrapper intentionally does not fabricate or require success_evidence or other progression model fields. """ inner: Any = payload if isinstance(inner.get("output"), dict): inner = inner["output"] if envelope and isinstance(inner.get(envelope), dict): inner = inner[envelope] if not isinstance(inner, dict) or not inner: raise PipelineError(stage, "invalid_output", "The model returned an empty or invalid output object.") return inner def composition_body(progression: dict[str, Any], style: str) -> dict[str, Any]: if style == "bare": return progression body = {"progression": progression} return {"input": body} if style == "input" else body def instruction_body(progression: dict[str, Any], composition: dict[str, Any], style: str) -> dict[str, Any]: comp = {"output": composition} if style in {"nested_output", "input_nested_output"} else composition body = {"progression": progression, "composition": comp} return {"input": body} if style in {"input", "input_nested_output"} else body class ActivityPipeline: def __init__(self, settings: Settings, client: httpx.AsyncClient): settings.validate() self.settings = settings self.progression = StageClient("progression", settings.progression_api_url, client, settings.max_attempts) self.composition = StageClient("composition", settings.composition_api_url, client, settings.max_attempts) self.instruction = StageClient("instruction", settings.instruction_api_url, client, settings.max_attempts) async def generate(self, request: ActivityRequest) -> ActivityResponse: progression_raw = await self.progression.post(request.model_dump()) progression = unwrap_object(progression_raw, "progression", envelope="progression") composition_raw = await self.composition.post( composition_body(progression, self.settings.composition_input_style) ) composition = unwrap_object(composition_raw, "composition") title = composition.get("activity_title") description = composition.get("activity_description") if not isinstance(title, str) or not title.strip() or not isinstance(description, str) or not description.strip(): raise PipelineError("composition", "invalid_output", "Expected nonempty activity_title and activity_description strings.") cleaned_composition = {"activity_title": title.strip(), "activity_description": description.strip()} instruction_raw = await self.instruction.post( instruction_body(progression, cleaned_composition, self.settings.instruction_input_style) ) instruction = unwrap_object(instruction_raw, "instruction") try: final = Activity( activity_title=cleaned_composition["activity_title"], activity_description=cleaned_composition["activity_description"], instructions=instruction.get("instructions"), ) except ValidationError as exc: raise PipelineError("instruction", "invalid_output", "Expected a nonempty instructions list of strings.") from exc if any(not item.strip() for item in final.instructions): raise PipelineError("instruction", "invalid_output", "Instructions cannot contain blank steps.") return ActivityResponse(output=final)