Repository navigation
Dependabot/GitHub actions/dependencies a8cfc930ad #5467
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
wayu1689w-dev
wants to merge
12
commits into
github:main
Choose a base branch
from
wayu1689w-dev:dependabot/github_actions/dependencies-a8cfc930ad
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
61f46b3
Add AI Office Orchestrator (scoring, circuit breaker, failover, adapt…
claude eeeccce
Add durable metrics store, planner/classifier, CLI entry
claude 8afb8d8
Add critic and fact-check review pass
claude ae334c5
Fix critic: do not reject short valid answers
claude dd8968f
Remove committed __pycache__ files
claude 3a2911b
Remove AI Office Orchestrator (cancelled)
claude 747e74d
Restore AI Office Orchestrator
claude 5d63ca3
Add parallel ensemble mode with pluggable selection
claude 2a2e518
Add Grok (xAI) adapter, test, and provider reference
claude 426e2bb
Add ConsentGate: one-time, expiring, task-bound approval tokens for s…
claude 86efa77
Merge pull request #4 from wayu1689w-dev/claude/new-session-cec2ob
wayu1689w-dev 848a697
Merge branch 'main' into dependabot/github_actions/dependencies-a8cfc…
wayu1689w-dev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| metrics.db | ||
| __pycache__/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
| 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] | ||
|
wayu1689w-dev marked this conversation as resolved.
Resolved
|
||
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
|
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") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
|
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 | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.