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 iswritten anywhere.run_curate β given a set of candidates the user chose to keep:validation -> curation. This is the only path thatwrites to the library, and it's a separate call bydesign ("confirm before commit" β see product/UX notesin the system design doc)."""from __future__ import annotationsimport loggingfrom 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.0def _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 = Falsetry: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 = Nonewith 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 = attemptssp.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 = Trueresult = RetrievalResult(candidates=[], index_version="unavailable", latency_ms=0)# --- Ranking (non-fatal: falls back to vector-similarity order on failure) ---ranked_candidates = result.candidateswith 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_fallbackelse:sp.status = "ok" # nothing to rank isn't a ranking failurereturn 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 = attemptssp.status = "ok"_curation_breaker.record_success()added = curation_result.addedskipped_duplicates = curation_result.skipped_duplicatesexcept (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),)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Strata β FastAPI entrypoint.Endpoints:GET /health liveness probeGET /metrics per-agent success rate / latency (observability layer)POST /search run a query through orchestrator: understand -> retrieve -> rankPOST /curate validate + write chosen candidates into the library (the onlyendpoint that writes anything β separate from /search by design)GET /library browse what's been curated so far"""from __future__ import annotationsimport loggingfrom fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom app.orchestrator import run_search, run_curatefrom app.core.contracts import SearchResponse, CurateResponse, RetrievalCandidate, LibraryItemfrom app.core.tracing import get_agent_statsfrom app.agents.curation_agent import list_librarylogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")app = FastAPI(title="Strata",description="Query-based agent for retrieving and curating landscape specimen imagery.",version="0.2.0",)class SearchRequest(BaseModel):query: str = Field(..., min_length=1, max_length=500)top_k: int = Field(default=10, ge=1, le=50)class CurateRequest(BaseModel):items: list[RetrievalCandidate] = Field(..., min_length=1)@app.get("/health")def health():return {"status": "ok"}@app.get("/metrics")def metrics():return get_agent_stats()@app.post("/search", response_model=SearchResponse)def search(req: SearchRequest):try:return run_search(req.query, top_k=req.top_k)except ValueError as e:raise HTTPException(status_code=400, detail=str(e))@app.post("/curate", response_model=CurateResponse)def curate(req: CurateRequest):return run_curate(req.items)@app.get("/library", response_model=list[LibraryItem])def library(limit: int = 50):return list_library(limit=limit)
requirements.txt+49-146