diff --git a/ai_office_orchestrator/.env.example b/ai_office_orchestrator/.env.example new file mode 100644 index 00000000000..f96ca595633 --- /dev/null +++ b/ai_office_orchestrator/.env.example @@ -0,0 +1,8 @@ +# Set real values in your environment, never commit them. +OPENAI_API_KEY= +GEMINI_API_KEY= +ANTHROPIC_API_KEY= +MODEL_API_KEY= +CANVA_ACCESS_TOKEN= +XAI_API_KEY= +# optional overrides: XAI_MODEL, XAI_BASE_URL diff --git a/ai_office_orchestrator/.gitignore b/ai_office_orchestrator/.gitignore new file mode 100644 index 00000000000..ee2b57a1731 --- /dev/null +++ b/ai_office_orchestrator/.gitignore @@ -0,0 +1,2 @@ +metrics.db +__pycache__/ diff --git a/ai_office_orchestrator/README.md b/ai_office_orchestrator/README.md new file mode 100644 index 00000000000..a8a76532b45 --- /dev/null +++ b/ai_office_orchestrator/README.md @@ -0,0 +1,10 @@ +# AI Office Orchestrator + +Task -> score providers (health, quality, success, speed, cost) -> circuit breaker +-> adapter -> output checker -> failover to next provider. + +- Side-effect tasks (email, publish, calendar) need `approved=True` and never fail over. +- Optional `ConsentGate` (app/core/consent.py): one-time, expiring token bound to the exact task; replays and mismatches are refused. +- Credentials come from environment variables only (see `.env.example`). +- Adapters are unverified against live APIs. Run tests: `python -m unittest discover -s tests -t .` +- Providers: openai, gemini, claude, grok (xAI), meta, canva. See `docs_provider_reference.md`. diff --git a/ai_office_orchestrator/app/__init__.py b/ai_office_orchestrator/app/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/ai_office_orchestrator/app/__main__.py b/ai_office_orchestrator/app/__main__.py new file mode 100644 index 00000000000..a4f8cb06b37 --- /dev/null +++ b/ai_office_orchestrator/app/__main__.py @@ -0,0 +1,13 @@ +import sys + +from app.adapters.factory import build_adapters +from app.core.metrics import MetricsStore +from app.core.orchestrator import Orchestrator +from app.core.planner import plan + +if __name__ == "__main__": + prompt = " ".join(sys.argv[1:]) or "hello" + orch = Orchestrator(build_adapters(), metrics=MetricsStore("metrics.db")) + for task in plan(prompt): + r = orch.run(task) + print(f"[{r.provider}] {r.output}") diff --git a/ai_office_orchestrator/app/adapters/__init__.py b/ai_office_orchestrator/app/adapters/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/ai_office_orchestrator/app/adapters/base.py b/ai_office_orchestrator/app/adapters/base.py new file mode 100644 index 00000000000..3191ebdeb3b --- /dev/null +++ b/ai_office_orchestrator/app/adapters/base.py @@ -0,0 +1,27 @@ +import os + + +class MissingCredential(Exception): + pass + + +class BaseAdapter: + name = "base" + env_key = "" + kinds: tuple = () + metrics: dict = {} + + def credential(self): + value = os.getenv(self.env_key, "").strip() + if not value: + raise MissingCredential(f"Missing required environment variable: {self.env_key}") + return value + + def healthy(self) -> bool: + return bool(os.getenv(self.env_key, "").strip()) + + def profile(self): + return {"kinds": self.kinds, "metrics": self.metrics} + + def run(self, task) -> str: + raise NotImplementedError diff --git a/ai_office_orchestrator/app/adapters/factory.py b/ai_office_orchestrator/app/adapters/factory.py new file mode 100644 index 00000000000..df3ff33d2df --- /dev/null +++ b/ai_office_orchestrator/app/adapters/factory.py @@ -0,0 +1,5 @@ +from .providers import ALL + + +def build_adapters(): + return [cls() for cls in ALL] diff --git a/ai_office_orchestrator/app/adapters/providers.py b/ai_office_orchestrator/app/adapters/providers.py new file mode 100644 index 00000000000..1ec7c2cc4a2 --- /dev/null +++ b/ai_office_orchestrator/app/adapters/providers.py @@ -0,0 +1,92 @@ +"""Real API adapters. SDKs are imported lazily so the core runs without them. +These are NOT verified against live APIs: no credentials were available.""" +import json +import os +import urllib.request + +from .base import BaseAdapter + + +class OpenAIAdapter(BaseAdapter): + name, env_key = "openai", "OPENAI_API_KEY" + kinds = ("text", "code", "research") + metrics = dict(quality=0.9, success=0.9, speed=0.7, cost=0.4) + + def run(self, task): + from openai import OpenAI + client = OpenAI(api_key=self.credential()) + r = client.responses.create(model="gpt-5", input=task.prompt) + return r.output_text + + +class GeminiAdapter(BaseAdapter): + name, env_key = "gemini", "GEMINI_API_KEY" + kinds = ("text", "research", "image", "video") + metrics = dict(quality=0.85, success=0.9, speed=0.8, cost=0.6) + + def run(self, task): + from google import genai + client = genai.Client(api_key=self.credential()) + return client.models.generate_content(model="gemini-2.5-pro", contents=task.prompt).text + + +class ClaudeAdapter(BaseAdapter): + name, env_key = "claude", "ANTHROPIC_API_KEY" + kinds = ("text", "code", "research") + metrics = dict(quality=0.92, success=0.9, speed=0.7, cost=0.4) + + def run(self, task): + import anthropic + client = anthropic.Anthropic(api_key=self.credential()) + m = client.messages.create(model="claude-sonnet-5-5", max_tokens=2048, + messages=[{"role": "user", "content": task.prompt}]) + return "".join(b.text for b in m.content if b.type == "text") + + +class GrokAdapter(BaseAdapter): + """xAI Grok via its OpenAI-compatible endpoint. Base URL and model name are + unverified (docs.x.ai was unreachable); override with XAI_BASE_URL / XAI_MODEL.""" + name, env_key = "grok", "XAI_API_KEY" + kinds = ("text", "code", "research") + metrics = dict(quality=0.85, success=0.85, speed=0.75, cost=0.5) + + def run(self, task): + from openai import OpenAI + client = OpenAI(api_key=self.credential(), + base_url=os.getenv("XAI_BASE_URL", "https://api.x.ai/v1")) + r = client.chat.completions.create( + model=os.getenv("XAI_MODEL", "grok-4"), + messages=[{"role": "user", "content": task.prompt}]) + return r.choices[0].message.content + + +class MetaAdapter(BaseAdapter): + name, env_key = "meta", "MODEL_API_KEY" + kinds = ("text",) + metrics = dict(quality=0.75, success=0.8, speed=0.8, cost=0.7) + base = "https://api.meta.ai/v1" + + def run(self, task): + # Endpoint path/body are assumptions; confirm against Meta's docs. + req = urllib.request.Request( + f"{self.base}/chat/completions", + data=json.dumps({"messages": [{"role": "user", "content": task.prompt}]}).encode(), + headers={"Authorization": f"Bearer {self.credential()}", + "Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=60) as r: + return json.load(r)["choices"][0]["message"]["content"] + + +class CanvaAdapter(BaseAdapter): + name, env_key = "canva", "CANVA_ACCESS_TOKEN" + kinds = ("design",) + metrics = dict(quality=0.8, success=0.8, speed=0.5, cost=0.5) + + def auth_check(self): + return self.healthy() + + def run(self, task): + raise NotImplementedError("Canva requires an OAuth flow; not implemented") + + +ALL = [OpenAIAdapter, GeminiAdapter, ClaudeAdapter, GrokAdapter, MetaAdapter, CanvaAdapter] diff --git a/ai_office_orchestrator/app/core/__init__.py b/ai_office_orchestrator/app/core/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/ai_office_orchestrator/app/core/checker.py b/ai_office_orchestrator/app/core/checker.py new file mode 100644 index 00000000000..0459cc6a1df --- /dev/null +++ b/ai_office_orchestrator/app/core/checker.py @@ -0,0 +1,7 @@ +def check_output(output) -> tuple[bool, str]: + """Return (ok, reason). Rejects empty or placeholder output.""" + if output is None or not str(output).strip(): + return False, "empty output" + if str(output).strip().lower() in {"none", "null", "error", "n/a"}: + return False, "placeholder output" + return True, "ok" diff --git a/ai_office_orchestrator/app/core/circuit_breaker.py b/ai_office_orchestrator/app/core/circuit_breaker.py new file mode 100644 index 00000000000..396a48b5a46 --- /dev/null +++ b/ai_office_orchestrator/app/core/circuit_breaker.py @@ -0,0 +1,26 @@ +import time + + +class CircuitBreaker: + CLOSED, OPEN, HALF_OPEN = "CLOSED", "OPEN", "HALF_OPEN" + + def __init__(self, threshold=3, recovery_seconds=30, clock=time.monotonic): + self.threshold, self.recovery, self.clock = threshold, recovery_seconds, clock + self.failures, self.opened_at, self._state = 0, 0.0, self.CLOSED + + @property + def state(self): + if self._state == self.OPEN and self.clock() - self.opened_at >= self.recovery: + self._state = self.HALF_OPEN + return self._state + + def allow(self): + return self.state != self.OPEN + + def success(self): + self.failures, self._state = 0, self.CLOSED + + def failure(self): + self.failures += 1 + if self._state == self.HALF_OPEN or self.failures >= self.threshold: + self._state, self.opened_at = self.OPEN, self.clock() diff --git a/ai_office_orchestrator/app/core/consent.py b/ai_office_orchestrator/app/core/consent.py new file mode 100644 index 00000000000..e38aea98e43 --- /dev/null +++ b/ai_office_orchestrator/app/core/consent.py @@ -0,0 +1,40 @@ +"""Consent gate for side-effect tasks (send email, publish, create event ...). + +A token is bound to the exact task content (kind + prompt), expires, and can be +used once. Consuming it before the call means a retry or failover can never +repeat the action; a new approval is needed to try again.""" +import hashlib +import json +import secrets +import time + + +def fingerprint(task) -> str: + return hashlib.sha256(f"{task.kind}\x00{task.prompt}".encode()).hexdigest() + + +class ConsentGate: + def __init__(self, ttl=300, audit_path=None, clock=time.time): + self.ttl, self.audit_path, self.clock = ttl, audit_path, clock + self._tokens = {} # token -> (fingerprint, expires_at) + + def approve(self, task) -> str: + """Called by a human-facing layer after the user confirmed this task.""" + token = secrets.token_urlsafe(16) + self._tokens[token] = (fingerprint(task), self.clock() + self.ttl) + self._log("approved", task) + return token + + def consume(self, task, token) -> bool: + entry = self._tokens.pop(token, None) if token else None + ok = bool(entry) and entry[0] == fingerprint(task) and self.clock() <= entry[1] + self._log("consumed" if ok else "denied", task) + return ok + + def _log(self, event, task): + if not self.audit_path: + return + row = {"t": self.clock(), "event": event, "kind": task.kind, + "fp": fingerprint(task)[:12]} # no prompt text, no token in the log + with open(self.audit_path, "a") as f: + f.write(json.dumps(row) + "\n") diff --git a/ai_office_orchestrator/app/core/critic.py b/ai_office_orchestrator/app/core/critic.py new file mode 100644 index 00000000000..e0161a51718 --- /dev/null +++ b/ai_office_orchestrator/app/core/critic.py @@ -0,0 +1,34 @@ +"""Second-pass review. Uses a reviewer adapter (an LLM) when given; otherwise +falls back to cheap heuristics. Returns (ok, reason).""" +import re + +_REFUSAL = re.compile(r"\b(i cannot|i can't|as an ai|unable to assist)\b", re.I) + + +def heuristic_review(task, output: str): + text = str(output).strip() + if _REFUSAL.search(text[:200]): + return False, "looks like a refusal" + return True, "ok" + + +def fact_check(output: str): + """Flag unsupported claims: numbers/URLs present without any source marker. + Heuristic only; real fact-checking needs a retrieval step.""" + has_claims = bool(re.search(r"\d{2,}|https?://", output)) + has_source = bool(re.search(r"(source|อ้างอิง|ที่มา|https?://)", output, re.I)) + if has_claims and not has_source: + return False, "numeric claims without source" + return True, "ok" + + +def review(task, output, reviewer=None, strict_facts=False): + if reviewer is not None: + verdict = str(reviewer.run(type(task)("text", + f"Reply PASS or FAIL: does this answer the request?\nRequest: {task.prompt}\nAnswer: {output}"))) + if verdict.strip().upper().startswith("FAIL"): + return False, "reviewer said FAIL" + ok, why = heuristic_review(task, output) + if ok and strict_facts: + ok, why = fact_check(output) + return ok, why diff --git a/ai_office_orchestrator/app/core/metrics.py b/ai_office_orchestrator/app/core/metrics.py new file mode 100644 index 00000000000..e47c2e46872 --- /dev/null +++ b/ai_office_orchestrator/app/core/metrics.py @@ -0,0 +1,26 @@ +import sqlite3 +import time + + +class MetricsStore: + """Durable per-provider outcomes (SQLite). Feeds scoring with real success/speed.""" + + def __init__(self, path=":memory:"): + self.db = sqlite3.connect(path) + self.db.execute("CREATE TABLE IF NOT EXISTS runs(" + "provider TEXT, kind TEXT, ok INTEGER, seconds REAL, ts REAL)") + + def record(self, provider, kind, ok, seconds): + self.db.execute("INSERT INTO runs VALUES(?,?,?,?,?)", + (provider, kind, int(ok), seconds, time.time())) + self.db.commit() + + def observed(self, provider, kind, window=50): + rows = self.db.execute( + "SELECT ok, seconds FROM runs WHERE provider=? AND kind=? " + "ORDER BY ts DESC LIMIT ?", (provider, kind, window)).fetchall() + if not rows: + return {} + success = sum(r[0] for r in rows) / len(rows) + avg = sum(r[1] for r in rows) / len(rows) + return {"success": success, "speed": 1 / (1 + avg)} # 0..1, faster = higher diff --git a/ai_office_orchestrator/app/core/orchestrator.py b/ai_office_orchestrator/app/core/orchestrator.py new file mode 100644 index 00000000000..afe9bb76a03 --- /dev/null +++ b/ai_office_orchestrator/app/core/orchestrator.py @@ -0,0 +1,111 @@ +import time +from concurrent.futures import ThreadPoolExecutor + +from .checker import check_output +from .critic import review +from .circuit_breaker import CircuitBreaker +from .scoring import score +from .task import Result + + +class OrchestratorError(Exception): + pass + + +class Orchestrator: + def __init__(self, adapters, max_attempts=3, breaker_factory=CircuitBreaker, metrics=None, + reviewer=None, strict_facts=False, consent=None): + self.consent = consent + self.reviewer, self.strict_facts = reviewer, strict_facts + self.metrics = metrics + self.adapters = {a.name: a for a in adapters} + self.breakers = {a.name: breaker_factory() for a in adapters} + self.max_attempts = max_attempts + + def ranked(self, task): + scored = [] + for name, a in self.adapters.items(): + if not self.breakers[name].allow(): + continue + prof = a.profile() + if self.metrics: + prof = {**prof, "metrics": {**prof.get("metrics", {}), + **self.metrics.observed(name, task.kind)}} + s = score(prof, task.kind, a.healthy()) + if s >= 0: + scored.append((s, name)) + return [n for _, n in sorted(scored, reverse=True)] + + def run(self, task) -> Result: + # Consent gate: side-effect tasks need approval and never fail over, + # so a timeout can't cause a duplicate email/publish/event. + if task.side_effect: + if self.consent is not None: + if not self.consent.consume(task, task.meta.get("consent_token")): + raise OrchestratorError("side-effect task requires a valid one-time consent token") + elif not task.approved: + raise OrchestratorError("side-effect task requires approval") + attempts = [] + candidates = self.ranked(task) + if task.side_effect: + candidates = candidates[:1] + for name in candidates[: self.max_attempts]: + t0 = time.monotonic() + try: + out = self.adapters[name].run(task) + except Exception as e: # noqa: BLE001 + self._rec(name, task, False, t0) + self.breakers[name].failure() + attempts.append((name, f"error: {e}")) + continue + ok, why = check_output(out) + if ok: + ok, why = review(task, out, self.reviewer, self.strict_facts) + self._rec(name, task, ok, t0) + if ok: + self.breakers[name].success() + attempts.append((name, "ok")) + return Result(name, out, attempts) + self.breakers[name].failure() + attempts.append((name, f"rejected: {why}")) + raise OrchestratorError(f"no provider produced valid output: {attempts}") + + def _rec(self, name, task, ok, t0): + if self.metrics: + self.metrics.record(name, task.kind, ok, time.monotonic() - t0) + + def run_ensemble(self, task, n=2, pick=None): + """Call the top-n providers in parallel, keep outputs that pass the + checker and critic, then choose one. `pick(task, {name: output})` + returns a name; default is the highest-ranked passing provider. + Side-effect tasks are refused: parallel calls would duplicate them.""" + if task.side_effect: + raise OrchestratorError("ensemble not allowed for side-effect tasks") + names = self.ranked(task)[:n] + if not names: + raise OrchestratorError("no eligible provider") + + def call(name): + t0 = time.monotonic() + try: + out = self.adapters[name].run(task) + except Exception as e: # noqa: BLE001 + self._rec(name, task, False, t0) + self.breakers[name].failure() + return name, None, f"error: {e}" + ok, why = check_output(out) + if ok: + ok, why = review(task, out, self.reviewer, self.strict_facts) + self._rec(name, task, ok, t0) + (self.breakers[name].success if ok else self.breakers[name].failure)() + return name, (out if ok else None), why + + with ThreadPoolExecutor(max_workers=len(names)) as ex: + rows = list(ex.map(call, names)) + attempts = [(n_, "ok" if o is not None else w) for n_, o, w in rows] + good = {n_: o for n_, o, _ in rows if o is not None} + if not good: + raise OrchestratorError(f"no provider produced valid output: {attempts}") + chosen = pick(task, good) if pick and len(good) > 1 else next( + n_ for n_ in names if n_ in good) + return Result(chosen, good[chosen], attempts) diff --git a/ai_office_orchestrator/app/core/planner.py b/ai_office_orchestrator/app/core/planner.py new file mode 100644 index 00000000000..16074a7673c --- /dev/null +++ b/ai_office_orchestrator/app/core/planner.py @@ -0,0 +1,20 @@ +from .task import Task + +_KEYWORDS = [("code", ("code", "bug", "function", "script", "โค้ด")), + ("image", ("image", "picture", "logo", "รูป")), + ("video", ("video", "วิดีโอ")), + ("design", ("design", "poster", "canva", "ออกแบบ")), + ("research", ("research", "compare", "ค้นคว้า", "วิจัย"))] + + +def classify(prompt: str) -> str: + p = prompt.lower() + for kind, words in _KEYWORDS: + if any(w in p for w in words): + return kind + return "text" + + +def plan(prompt: str) -> list[Task]: + """Minimal planner: one classified task. Extend to multi-step later.""" + return [Task(classify(prompt), prompt)] diff --git a/ai_office_orchestrator/app/core/scoring.py b/ai_office_orchestrator/app/core/scoring.py new file mode 100644 index 00000000000..6f4309857ef --- /dev/null +++ b/ai_office_orchestrator/app/core/scoring.py @@ -0,0 +1,12 @@ +WEIGHTS = dict(health=0.30, quality=0.30, success=0.25, speed=0.10, cost=0.05) + + +def score(profile: dict, kind: str, healthy: bool) -> float: + """Each metric is 0..1 (higher is better). -1 = not eligible.""" + if not healthy or kind not in profile.get("kinds", ()): + return -1.0 + m = profile.get("metrics", {}) + total = WEIGHTS["health"] + for k in ("quality", "success", "speed", "cost"): + total += WEIGHTS[k] * m.get(k, 0.5) + return round(total, 4) diff --git a/ai_office_orchestrator/app/core/task.py b/ai_office_orchestrator/app/core/task.py new file mode 100644 index 00000000000..97d9a923c2f --- /dev/null +++ b/ai_office_orchestrator/app/core/task.py @@ -0,0 +1,17 @@ +from dataclasses import dataclass, field + + +@dataclass +class Task: + kind: str # text | code | image | video | research ... + prompt: str + side_effect: bool = False # send email, publish, create event ... + approved: bool = False # consent gate for side-effect tasks + meta: dict = field(default_factory=dict) + + +@dataclass +class Result: + provider: str + output: str + attempts: list = field(default_factory=list) diff --git a/ai_office_orchestrator/docs_provider_reference.md b/ai_office_orchestrator/docs_provider_reference.md new file mode 100644 index 00000000000..5eea44a2d5c --- /dev/null +++ b/ai_office_orchestrator/docs_provider_reference.md @@ -0,0 +1,15 @@ +# Provider reference (UNVERIFIED) + +docs.x.ai, ai.google.dev and platform.openai.com were not reachable from the +build session (network allowlist), so nothing here was checked against live docs. +Confirm each item on the official site before relying on it. + +| Provider | Env var | SDK / endpoint used in code | Model in code | Status | +|---|---|---|---|---| +| OpenAI | OPENAI_API_KEY | `openai` SDK, Responses API | gpt-5 | unverified | +| Gemini (Google AI) | GEMINI_API_KEY | `google-genai`, `models.generate_content` | gemini-2.5-pro | unverified | +| Grok (xAI) | XAI_API_KEY | `openai` SDK, base_url https://api.x.ai/v1, chat.completions | grok-4 (override XAI_MODEL) | unverified | +| Claude | ANTHROPIC_API_KEY | `anthropic` SDK, Messages API | claude-sonnet-5-5 | unverified | + +Note: the connected "Gemini" MCP connector is Gemini Trading (crypto exchange), +not Google Gemini AI. Do not use it for model calls. diff --git a/ai_office_orchestrator/requirements.txt b/ai_office_orchestrator/requirements.txt new file mode 100644 index 00000000000..c41b78ee579 --- /dev/null +++ b/ai_office_orchestrator/requirements.txt @@ -0,0 +1,3 @@ +openai +google-genai +anthropic diff --git a/ai_office_orchestrator/tests/__init__.py b/ai_office_orchestrator/tests/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/ai_office_orchestrator/tests/test_core.py b/ai_office_orchestrator/tests/test_core.py new file mode 100644 index 00000000000..a94a7ac41a7 --- /dev/null +++ b/ai_office_orchestrator/tests/test_core.py @@ -0,0 +1,155 @@ +import os +import unittest + +from app.adapters.base import BaseAdapter, MissingCredential +from app.core.circuit_breaker import CircuitBreaker +from app.core.orchestrator import Orchestrator, OrchestratorError +from app.core.task import Task + + +class Fake(BaseAdapter): + kinds = ("text",) + + def __init__(self, name, out=None, exc=None, q=0.5): + self.name, self.out, self.exc = name, out, exc + self.metrics = dict(quality=q, success=0.5, speed=0.5, cost=0.5) + self.calls = 0 + + def healthy(self): + return True + + def run(self, task): + self.calls += 1 + if self.exc: + raise self.exc + return self.out + + +class Tests(unittest.TestCase): + def test_missing_key(self): + os.environ.pop("X_KEY", None) + a = BaseAdapter(); a.env_key = "X_KEY" + with self.assertRaises(MissingCredential): + a.credential() + + def test_grok_registered_and_needs_key(self): + from app.adapters.factory import build_adapters + g = next(a for a in build_adapters() if a.name == "grok") + os.environ.pop("XAI_API_KEY", None) + self.assertFalse(g.healthy()) + with self.assertRaises(MissingCredential): + g.credential() + os.environ["XAI_API_KEY"] = "dummy" + try: + self.assertTrue(g.healthy()) + finally: + os.environ.pop("XAI_API_KEY", None) + + def test_consent_token_bound_single_use_and_expiring(self): + from app.core.consent import ConsentGate + now = [1000.0] + gate = ConsentGate(ttl=60, clock=lambda: now[0]) + mk = lambda p: Task("text", p, side_effect=True) + orch = Orchestrator([Fake("a", out="sent")], consent=gate) + + t = mk("email bob") # no token -> refused + with self.assertRaises(OrchestratorError): + orch.run(t) + + t.meta["consent_token"] = gate.approve(t) # approved -> runs once + self.assertEqual(orch.run(t).output, "sent") + with self.assertRaises(OrchestratorError): # replay refused + orch.run(t) + + other = mk("email eve") # token for a different task + other.meta["consent_token"] = gate.approve(mk("email bob")) + with self.assertRaises(OrchestratorError): + orch.run(other) + + late = mk("email amy") # expired token + late.meta["consent_token"] = gate.approve(late) + now[0] += 61 + with self.assertRaises(OrchestratorError): + orch.run(late) + + def test_failover(self): + a, b = Fake("a", exc=RuntimeError("down"), q=0.9), Fake("b", out="hi") + r = Orchestrator([a, b]).run(Task("text", "x")) + self.assertEqual(r.provider, "b") + + def test_reject_empty(self): + a, b = Fake("a", out=" ", q=0.9), Fake("b", out="ok") + self.assertEqual(Orchestrator([a, b]).run(Task("text", "x")).provider, "b") + + def test_all_fail(self): + with self.assertRaises(OrchestratorError): + Orchestrator([Fake("a", out="")]).run(Task("text", "x")) + + def test_circuit(self): + t = [0.0] + cb = CircuitBreaker(2, 30, clock=lambda: t[0]) + cb.failure(); cb.failure() + self.assertFalse(cb.allow()) + t[0] = 31 + self.assertEqual(cb.state, "HALF_OPEN") + cb.success() + self.assertEqual(cb.state, "CLOSED") + + def test_side_effect_needs_approval_and_no_failover(self): + a, b = Fake("a", exc=RuntimeError("t/o"), q=0.9), Fake("b", out="sent") + o = Orchestrator([a, b]) + with self.assertRaises(OrchestratorError): + o.run(Task("text", "x", side_effect=True)) + with self.assertRaises(OrchestratorError): + o.run(Task("text", "x", side_effect=True, approved=True)) + self.assertEqual(b.calls, 0) + + +if __name__ == "__main__": + unittest.main() + + +class TestMetricsPlanner(unittest.TestCase): + def test_metrics_shift_ranking(self): + from app.core.metrics import MetricsStore + m = MetricsStore() + for _ in range(5): + m.record("a", "text", False, 1.0) + m.record("b", "text", True, 0.1) + o = Orchestrator([Fake("a", out="A", q=0.9), Fake("b", out="B", q=0.5)], metrics=m) + self.assertEqual(o.ranked(Task("text", "x"))[0], "b") + + def test_classify(self): + from app.core.planner import classify + self.assertEqual(classify("fix this bug"), "code") + self.assertEqual(classify("hello"), "text") + + +class TestCritic(unittest.TestCase): + def test_refusal_triggers_failover(self): + a, b = Fake("a", out="I cannot help with that", q=0.9), Fake("b", out="Answer") + self.assertEqual(Orchestrator([a, b]).run(Task("text", "x")).provider, "b") + + def test_unsourced_numbers_rejected_when_strict(self): + a, b = Fake("a", out="Revenue grew 45%", q=0.9), Fake("b", out="Grew 45% (source: report)") + o = Orchestrator([a, b], strict_facts=True) + self.assertEqual(o.run(Task("text", "x")).provider, "b") + + +class TestEnsemble(unittest.TestCase): + def test_picks_best_valid(self): + a, b = Fake("a", out="", q=0.9), Fake("b", out="B", q=0.5) + r = Orchestrator([a, b]).run_ensemble(Task("text", "x"), n=2) + self.assertEqual(r.provider, "b") + self.assertEqual(a.calls + b.calls, 2) + + def test_custom_pick(self): + a, b = Fake("a", out="short", q=0.9), Fake("b", out="much longer answer", q=0.5) + longest = lambda t, g: max(g, key=lambda k: len(g[k])) + r = Orchestrator([a, b]).run_ensemble(Task("text", "x"), n=2, pick=longest) + self.assertEqual(r.provider, "b") + + def test_refuses_side_effects(self): + with self.assertRaises(OrchestratorError): + Orchestrator([Fake("a", out="x")]).run_ensemble( + Task("text", "x", side_effect=True, approved=True))