Spaces:
Running
Running
Deploy 5333a833
Browse files- backend/app.py +2 -1
- backend/integrations/llm_factory.py +3 -3
- eval_data/ragas_eval.py +18 -4
- tests/test_cloudflare_provider.py +8 -0
backend/app.py
CHANGED
|
@@ -542,7 +542,8 @@ def _ragas_worker(
|
|
| 542 |
result_callback=None,
|
| 543 |
) -> None:
|
| 544 |
"""Daemon thread body: compute scores, stash them for the Timer poll."""
|
| 545 |
-
|
|
|
|
| 546 |
def report_progress(report):
|
| 547 |
with _ragas_lock:
|
| 548 |
entry = _ragas_tasks.get(task_id)
|
|
|
|
| 542 |
result_callback=None,
|
| 543 |
) -> None:
|
| 544 |
"""Daemon thread body: compute scores, stash them for the Timer poll."""
|
| 545 |
+
from eval_data.ragas_eval import ragas_time_limits
|
| 546 |
+
timeout, _ = ragas_time_limits(inputs.get("endpoint"))
|
| 547 |
def report_progress(report):
|
| 548 |
with _ragas_lock:
|
| 549 |
entry = _ragas_tasks.get(task_id)
|
backend/integrations/llm_factory.py
CHANGED
|
@@ -123,12 +123,12 @@ def _get_cloudflare_chat(**kwargs: Any) -> Optional[Any]:
|
|
| 123 |
import httpx
|
| 124 |
timeout = kwargs.pop("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 125 |
if isinstance(timeout, (int, float)):
|
| 126 |
-
timeout = httpx.Timeout(timeout, connect=min(float(timeout),
|
| 127 |
# Retry only failures while establishing a connection, before an HTTP
|
| 128 |
# request is sent. Preserve normal TLS certificate and hostname checks.
|
| 129 |
# IPv6 is unavailable on the hosted Space; keep DNS and TLS SNI intact.
|
| 130 |
-
kwargs.setdefault("http_client", httpx.Client(transport=httpx.HTTPTransport(local_address="0.0.0.0", retries=
|
| 131 |
-
kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=httpx.AsyncHTTPTransport(local_address="0.0.0.0", retries=
|
| 132 |
kwargs["timeout"] = timeout
|
| 133 |
kwargs.setdefault("max_retries", 0)
|
| 134 |
kwargs["max_tokens"] = max(int(kwargs.get("max_tokens") or DEFAULT_OUTPUT_TOKENS), 4096)
|
|
|
|
| 123 |
import httpx
|
| 124 |
timeout = kwargs.pop("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 125 |
if isinstance(timeout, (int, float)):
|
| 126 |
+
timeout = httpx.Timeout(timeout, connect=min(float(timeout), 4.0))
|
| 127 |
# Retry only failures while establishing a connection, before an HTTP
|
| 128 |
# request is sent. Preserve normal TLS certificate and hostname checks.
|
| 129 |
# IPv6 is unavailable on the hosted Space; keep DNS and TLS SNI intact.
|
| 130 |
+
kwargs.setdefault("http_client", httpx.Client(transport=httpx.HTTPTransport(local_address="0.0.0.0", retries=5), timeout=timeout))
|
| 131 |
+
kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=httpx.AsyncHTTPTransport(local_address="0.0.0.0", retries=5), timeout=timeout))
|
| 132 |
kwargs["timeout"] = timeout
|
| 133 |
kwargs.setdefault("max_retries", 0)
|
| 134 |
kwargs["max_tokens"] = max(int(kwargs.get("max_tokens") or DEFAULT_OUTPUT_TOKENS), 4096)
|
eval_data/ragas_eval.py
CHANGED
|
@@ -208,7 +208,7 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
|
|
| 208 |
from backend.integrations.llm_factory import create_llm
|
| 209 |
from backend.integrations.endpoints import EndpointConfig, get_endpoint
|
| 210 |
configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 211 |
-
timeout = 15
|
| 212 |
if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
|
| 213 |
import httpx
|
| 214 |
# LangChain caches HTTP clients for hashable timeout values.
|
|
@@ -220,7 +220,7 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
|
|
| 220 |
|
| 221 |
from backend.integrations.llm_factory import _get_cloudflare_chat, _get_groq_chat, _get_gemini_chat
|
| 222 |
|
| 223 |
-
llm = _get_cloudflare_chat(temperature=0, max_retries=0, timeout=
|
| 224 |
if llm is not None:
|
| 225 |
logger.info("RAGAS evaluator: using Cloudflare Workers AI")
|
| 226 |
return _wrap_evaluator(llm)
|
|
@@ -289,6 +289,20 @@ def _safe_metric_error(exc):
|
|
| 289 |
return "failed", type(exc).__name__
|
| 290 |
|
| 291 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
|
| 293 |
"""Run independent bounded RAGAS metrics, preserving successes and real failures.
|
| 294 |
|
|
@@ -299,8 +313,8 @@ def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=No
|
|
| 299 |
import queue
|
| 300 |
from contextvars import copy_context
|
| 301 |
started = time.monotonic()
|
| 302 |
-
total_budget =
|
| 303 |
-
per_metric = max(.05, float(metric_timeout
|
| 304 |
names = ["context_precision", "faithfulness"]
|
| 305 |
if ground_truth:
|
| 306 |
names.append("context_recall")
|
|
|
|
| 208 |
from backend.integrations.llm_factory import create_llm
|
| 209 |
from backend.integrations.endpoints import EndpointConfig, get_endpoint
|
| 210 |
configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 211 |
+
timeout = 80 if getattr(configured, "name", "") == "Cloudflare" else 15
|
| 212 |
if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
|
| 213 |
import httpx
|
| 214 |
# LangChain caches HTTP clients for hashable timeout values.
|
|
|
|
| 220 |
|
| 221 |
from backend.integrations.llm_factory import _get_cloudflare_chat, _get_groq_chat, _get_gemini_chat
|
| 222 |
|
| 223 |
+
llm = _get_cloudflare_chat(temperature=0, max_retries=0, timeout=80)
|
| 224 |
if llm is not None:
|
| 225 |
logger.info("RAGAS evaluator: using Cloudflare Workers AI")
|
| 226 |
return _wrap_evaluator(llm)
|
|
|
|
| 289 |
return "failed", type(exc).__name__
|
| 290 |
|
| 291 |
|
| 292 |
+
def ragas_time_limits(endpoint=None):
|
| 293 |
+
"""Account for paced, remote Cloudflare inference in both deadlines."""
|
| 294 |
+
total = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "30")))
|
| 295 |
+
per_metric = max(.05, float(os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "12")))
|
| 296 |
+
name = endpoint if isinstance(endpoint, str) else getattr(endpoint, "name", "")
|
| 297 |
+
uses_cloudflare = str(name).lower() == "cloudflare" or (
|
| 298 |
+
not endpoint and bool(os.getenv("CLOUDFLARE_API_TOKEN") and os.getenv("CLOUDFLARE_ACCOUNT_ID"))
|
| 299 |
+
)
|
| 300 |
+
if uses_cloudflare:
|
| 301 |
+
total = max(total, float(os.getenv("OCR_CLOUDFLARE_RAGAS_TIMEOUT_SECONDS", "210")))
|
| 302 |
+
per_metric = max(per_metric, float(os.getenv("OCR_CLOUDFLARE_RAGAS_METRIC_TIMEOUT_SECONDS", "150")))
|
| 303 |
+
return total, per_metric
|
| 304 |
+
|
| 305 |
+
|
| 306 |
def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
|
| 307 |
"""Run independent bounded RAGAS metrics, preserving successes and real failures.
|
| 308 |
|
|
|
|
| 313 |
import queue
|
| 314 |
from contextvars import copy_context
|
| 315 |
started = time.monotonic()
|
| 316 |
+
total_budget, default_metric_timeout = ragas_time_limits(endpoint)
|
| 317 |
+
per_metric = max(.05, float(metric_timeout if metric_timeout is not None else default_metric_timeout))
|
| 318 |
names = ["context_precision", "faithfulness"]
|
| 319 |
if ground_truth:
|
| 320 |
names.append("context_recall")
|
tests/test_cloudflare_provider.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import pytest
|
| 2 |
|
| 3 |
from backend.integrations import llm_factory
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
def test_cloudflare_default_and_shared_pacing(monkeypatch):
|
|
@@ -22,3 +23,10 @@ def test_daily_budget_rejects_additional_attempts():
|
|
| 22 |
limiter._reserve()
|
| 23 |
with pytest.raises(ValueError, match='daily request budget'):
|
| 24 |
limiter._reserve()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import pytest
|
| 2 |
|
| 3 |
from backend.integrations import llm_factory
|
| 4 |
+
from eval_data.ragas_eval import ragas_time_limits
|
| 5 |
|
| 6 |
|
| 7 |
def test_cloudflare_default_and_shared_pacing(monkeypatch):
|
|
|
|
| 23 |
limiter._reserve()
|
| 24 |
with pytest.raises(ValueError, match='daily request budget'):
|
| 25 |
limiter._reserve()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_cloudflare_evaluation_has_room_for_paced_calls(monkeypatch):
|
| 29 |
+
monkeypatch.setenv('OCR_RAGAS_TIMEOUT_SECONDS', '30')
|
| 30 |
+
monkeypatch.setenv('OCR_RAGAS_METRIC_TIMEOUT_SECONDS', '12')
|
| 31 |
+
assert ragas_time_limits('Cloudflare') == (210, 150)
|
| 32 |
+
assert ragas_time_limits('Gemini') == (30, 12)
|