Spaces:
Build error
Build error
Create requirements.txt
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""Strata β Orchestrator.
The single place that: sequences sub-agent calls, enforces per-calltimeouts, applies retry/backoff, falls back on degraded dependencies,and emits one trace per request. Sub-agents never call each otherdirectly β everything routes through here so there is one place toreason about policy and one place to debug a bad result.
Two flows: run_search β read-only: query understanding -> retrieval -> ranking. Returns candidates for the user to review. Nothing is written anywhere. run_curate β given a set of candidates the user chose to keep: validation -> curation. This is the only path that writes to the library, and it's a separate call by design ("confirm before commit" β see product/UX notes in the system design doc)."""
from __future__ import annotationsimport logging
from app.core.contracts import ( QueryIntent, SearchResponse, RetrievalResult, AgentCallTrace, RetrievalCandidate, CurateResponse,)from app.core.reliability import ( retry_with_backoff, with_timeout, RetryableError, NonRetryableError, CircuitBreaker,)from app.core.security import validate_query, ValidationErrorfrom app.core import tracingfrom app.agents import ( query_understanding_agent, retrieval_agent, ranking_agent, validation_agent, curation_agent,)
logger = logging.getLogger("strata.orchestrator")
# One breaker per downstream dependency β trips independently, so a# struggling retrieval index doesn't take down curation writes and vice versa._retrieval_breaker = CircuitBreaker(failure_threshold=5, window_s=30.0, cooldown_s=20.0)_curation_breaker = CircuitBreaker(failure_threshold=3, window_s=30.0, cooldown_s=20.0)
RETRIEVAL_TIMEOUT_S = 3.0CURATION_TIMEOUT_S = 5.0
def _spans(trace: tracing.Trace) -> list[AgentCallTrace]: return [ AgentCallTrace(agent=s.agent, status=s.status, latency_ms=s.latency_ms, retries=s.retries) for s in trace.spans ]
# ---------------------------------------------------------------------# Search flow (read-only)# ---------------------------------------------------------------------
def run_search(raw_query: str, top_k: int = 10) -> SearchResponse: trace = tracing.Trace() degraded = False
try: validate_query(raw_query) except ValidationError as e: raise ValueError(f"invalid query: {e}") from e
# --- Query Understanding --- with tracing.span(trace, "query_understanding_agent") as sp: intent: QueryIntent = query_understanding_agent.parse(raw_query, top_k=top_k) sp.status = "ok"
# --- Retrieval (timeout + retry/backoff + circuit breaker + fallback) --- result: RetrievalResult | None = None with tracing.span(trace, "retrieval_agent") as sp: try: _retrieval_breaker.guard()
def _call(): return with_timeout(lambda: retrieval_agent.retrieve(intent), RETRIEVAL_TIMEOUT_S)
result, attempts = retry_with_backoff(_call, max_attempts=3) sp.retries = attempts sp.status = "ok" _retrieval_breaker.record_success()
except (RetryableError, NonRetryableError) as e: logger.warning("retrieval failed after retries, falling back: %s", e) _retrieval_breaker.record_failure() sp.status = "fallback" degraded = True result = RetrievalResult(candidates=[], index_version="unavailable", latency_ms=0)
# --- Ranking (non-fatal: falls back to vector-similarity order on failure) --- ranked_candidates = result.candidates with tracing.span(trace, "ranking_agent") as sp: if result.candidates: ranked_candidates, used_fallback = ranking_agent.rerank(raw_query, result.candidates) sp.status = "fallback" if used_fallback else "ok" degraded = degraded or used_fallback else: sp.status = "ok" # nothing to rank isn't a ranking failure
return SearchResponse( query=raw_query, results=ranked_candidates, trace_id=trace.trace_id, spans=_spans(trace), degraded=degraded, )
# ---------------------------------------------------------------------# Curate flow (the only path that writes to the library)# ---------------------------------------------------------------------
def run_curate(items: list[RetrievalCandidate]) -> CurateResponse: trace = tracing.Trace()
# --- Validation (read-only policy gate) --- with tracing.span(trace, "validation_agent") as sp: results = validation_agent.validate_batch(items) approved_ids = {r.candidate_id for r in results if r.approved} rejected = [r for r in results if not r.approved] sp.status = "ok"
approved_items = [c for c in items if c.id in approved_ids]
# --- Curation (write-scoped, timeout + retry + circuit breaker) --- added: list[str] = [] skipped_duplicates: list[str] = [] with tracing.span(trace, "curation_agent") as sp: if approved_items: try: _curation_breaker.guard()
def _call(): return with_timeout(lambda: curation_agent.curate(approved_items), CURATION_TIMEOUT_S)
curation_result, attempts = retry_with_backoff(_call, max_attempts=3) sp.retries = attempts sp.status = "ok" _curation_breaker.record_success() added = curation_result.added skipped_duplicates = curation_result.skipped_duplicates
except (RetryableError, NonRetryableError) as e: logger.error("curation failed after retries β nothing written for this batch: %s", e) _curation_breaker.record_failure() sp.status = "error" # no fallback here: a failed library write must not be silently # reported as success β the caller needs to know and retry. else: sp.status = "ok"
return CurateResponse( trace_id=trace.trace_id, added=added, skipped_duplicates=skipped_duplicates, rejected=rejected, spans=_spans(trace), )requirements.txtAdded+163