Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions ai_office_orchestrator/.env.example
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions ai_office_orchestrator/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
metrics.db
__pycache__/
10 changes: 10 additions & 0 deletions ai_office_orchestrator/README.md
Original file line number Diff line number Diff line change
@@ -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`.
Empty file.
13 changes: 13 additions & 0 deletions ai_office_orchestrator/app/__main__.py
Original file line number Diff line number Diff line change
@@ -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}")
Empty file.
27 changes: 27 additions & 0 deletions ai_office_orchestrator/app/adapters/base.py
Original file line number Diff line number Diff line change
@@ -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
5 changes: 5 additions & 0 deletions ai_office_orchestrator/app/adapters/factory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from .providers import ALL


def build_adapters():
return [cls() for cls in ALL]
92 changes: 92 additions & 0 deletions ai_office_orchestrator/app/adapters/providers.py
Original file line number Diff line number Diff line change
@@ -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")
Comment thread
wayu1689w-dev marked this conversation as resolved.
Resolved
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]
Comment thread
wayu1689w-dev marked this conversation as resolved.
Resolved
Empty file.
7 changes: 7 additions & 0 deletions ai_office_orchestrator/app/core/checker.py
Original file line number Diff line number Diff line change
@@ -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"
26 changes: 26 additions & 0 deletions ai_office_orchestrator/app/core/circuit_breaker.py
Original file line number Diff line number Diff line change
@@ -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()
40 changes: 40 additions & 0 deletions ai_office_orchestrator/app/core/consent.py
Original file line number Diff line number Diff line change
@@ -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()
Comment thread
wayu1689w-dev marked this conversation as resolved.
Resolved


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")
34 changes: 34 additions & 0 deletions ai_office_orchestrator/app/core/critic.py
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions ai_office_orchestrator/app/core/metrics.py
Original file line number Diff line number Diff line change
@@ -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)
Comment thread
wayu1689w-dev marked this conversation as resolved.
Resolved
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
Loading
Loading