From 61f46b3e88f22782f532581e2208dbc43e229d9c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:42:01 +0000 Subject: [PATCH 01/10] Add AI Office Orchestrator (scoring, circuit breaker, failover, adapters) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcmS3uz1Xhna1GGFydb --- ai_office_orchestrator/.env.example | 6 ++ ai_office_orchestrator/README.md | 8 ++ ai_office_orchestrator/app/__init__.py | 0 .../app/__pycache__/__init__.cpython-313.pyc | Bin 0 -> 154 bytes .../app/adapters/__init__.py | 0 .../__pycache__/__init__.cpython-313.pyc | Bin 0 -> 163 bytes .../adapters/__pycache__/base.cpython-313.pyc | Bin 0 -> 1867 bytes ai_office_orchestrator/app/adapters/base.py | 27 +++++++ .../app/adapters/factory.py | 5 ++ .../app/adapters/providers.py | 74 ++++++++++++++++++ ai_office_orchestrator/app/core/__init__.py | 0 .../core/__pycache__/__init__.cpython-313.pyc | Bin 0 -> 159 bytes .../core/__pycache__/checker.cpython-313.pyc | Bin 0 -> 694 bytes .../circuit_breaker.cpython-313.pyc | Bin 0 -> 2256 bytes .../__pycache__/orchestrator.cpython-313.pyc | Bin 0 -> 3483 bytes .../core/__pycache__/scoring.cpython-313.pyc | Bin 0 -> 968 bytes .../app/core/__pycache__/task.cpython-313.pyc | Bin 0 -> 1030 bytes ai_office_orchestrator/app/core/checker.py | 7 ++ .../app/core/circuit_breaker.py | 26 ++++++ .../app/core/orchestrator.py | 50 ++++++++++++ ai_office_orchestrator/app/core/scoring.py | 12 +++ ai_office_orchestrator/app/core/task.py | 17 ++++ ai_office_orchestrator/requirements.txt | 3 + ai_office_orchestrator/tests/__init__.py | 0 .../__pycache__/__init__.cpython-313.pyc | Bin 0 -> 156 bytes .../__pycache__/test_core.cpython-313.pyc | Bin 0 -> 5490 bytes ai_office_orchestrator/tests/test_core.py | 69 ++++++++++++++++ 27 files changed, 304 insertions(+) create mode 100644 ai_office_orchestrator/.env.example create mode 100644 ai_office_orchestrator/README.md create mode 100644 ai_office_orchestrator/app/__init__.py create mode 100644 ai_office_orchestrator/app/__pycache__/__init__.cpython-313.pyc create mode 100644 ai_office_orchestrator/app/adapters/__init__.py create mode 100644 ai_office_orchestrator/app/adapters/__pycache__/__init__.cpython-313.pyc create mode 100644 ai_office_orchestrator/app/adapters/__pycache__/base.cpython-313.pyc create mode 100644 ai_office_orchestrator/app/adapters/base.py create mode 100644 ai_office_orchestrator/app/adapters/factory.py create mode 100644 ai_office_orchestrator/app/adapters/providers.py create mode 100644 ai_office_orchestrator/app/core/__init__.py create mode 100644 ai_office_orchestrator/app/core/__pycache__/__init__.cpython-313.pyc create mode 100644 ai_office_orchestrator/app/core/__pycache__/checker.cpython-313.pyc create mode 100644 ai_office_orchestrator/app/core/__pycache__/circuit_breaker.cpython-313.pyc create mode 100644 ai_office_orchestrator/app/core/__pycache__/orchestrator.cpython-313.pyc create mode 100644 ai_office_orchestrator/app/core/__pycache__/scoring.cpython-313.pyc create mode 100644 ai_office_orchestrator/app/core/__pycache__/task.cpython-313.pyc create mode 100644 ai_office_orchestrator/app/core/checker.py create mode 100644 ai_office_orchestrator/app/core/circuit_breaker.py create mode 100644 ai_office_orchestrator/app/core/orchestrator.py create mode 100644 ai_office_orchestrator/app/core/scoring.py create mode 100644 ai_office_orchestrator/app/core/task.py create mode 100644 ai_office_orchestrator/requirements.txt create mode 100644 ai_office_orchestrator/tests/__init__.py create mode 100644 ai_office_orchestrator/tests/__pycache__/__init__.cpython-313.pyc create mode 100644 ai_office_orchestrator/tests/__pycache__/test_core.cpython-313.pyc create mode 100644 ai_office_orchestrator/tests/test_core.py diff --git a/ai_office_orchestrator/.env.example b/ai_office_orchestrator/.env.example new file mode 100644 index 000000000000..50c34ee384d0 --- /dev/null +++ b/ai_office_orchestrator/.env.example @@ -0,0 +1,6 @@ +# Set real values in your environment, never commit them. +OPENAI_API_KEY= +GEMINI_API_KEY= +ANTHROPIC_API_KEY= +MODEL_API_KEY= +CANVA_ACCESS_TOKEN= diff --git a/ai_office_orchestrator/README.md b/ai_office_orchestrator/README.md new file mode 100644 index 000000000000..550ac0d9a02b --- /dev/null +++ b/ai_office_orchestrator/README.md @@ -0,0 +1,8 @@ +# 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. +- Credentials come from environment variables only (see `.env.example`). +- Adapters are unverified against live APIs. Run tests: `python -m unittest discover -s tests -t .` diff --git a/ai_office_orchestrator/app/__init__.py b/ai_office_orchestrator/app/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/ai_office_orchestrator/app/__pycache__/__init__.cpython-313.pyc b/ai_office_orchestrator/app/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91c18de68f98c3dde0f07a8e16a2e04c2f55682d GIT binary patch literal 154 zcmey&%ge<81bn}KWr66&AOZ#$p^VQgK*m&tbOudEzm*I{OhDdekklejMUKEC9tHCQ$$Y literal 0 HcmV?d00001 diff --git a/ai_office_orchestrator/app/adapters/__init__.py b/ai_office_orchestrator/app/adapters/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/ai_office_orchestrator/app/adapters/__pycache__/__init__.cpython-313.pyc b/ai_office_orchestrator/app/adapters/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93586698776327a05add25c0c36b66cf193997e7 GIT binary patch literal 163 zcmey&%ge<81bn}KWr66&AOZ#$p^VQgK*m&tbOudEzm*I{OhDdekklejMUU_%qDt&B^OT8VHY;x?@sq|%}YRq=ssPB>jH_5d5!yUyD+ z3O)JMa*m1uC#0Ujtv&T$NKZBLA!r))(i1m?BSp%o@2%Hhqs-ykH*em|y!pO2v)!?= z5r!@C?%m@JnX&(<({E~EbU#O9muXCszGuL$usqY`EYm_2sTAtPfb4q}^r|IXhZ=;| zr9$|G%yN~m-=x6kX3*GW6$X;VK-MG(X)-A5p@JgDADFId+Uwr}uW{Qm4eLa~=tEX6 zs3NNCwo&K0E=F{{?$nwV*>PQe(lo4KB&q9bCb*tu+T3<C%(;`_0qgu2Qzawk0EPJfLm^OmG1p1Qb8})rDTw{DaUKkUj3z+CPy{u27xPnk9 zb-{cNgt}?kHCIIH9NDS5)xJs?$mm3raQ8QaUABVQYs-Pw{XTv3>>*pG8JC(S^($jJ za%l*=rNCuN52a57yLN@Kl~_Mkli$B?g3ZaLAX|>JXILRrh6$YZ(~Y2ta=@Q7O)RAx zx3^4i>^jy|Zp#4EShe_9Ijkw!aYcBYdl(=h2>K@97AgvEHhfVFvQS)ZtqFC@u$tVZ zgXeNEh95CfJ+D$RHNf)hg+GCD?mR+^y-rO$k3Ea+%^cj?zx6`yq;9@S-9Ad)?xf~+ z)PIwi*At(#uRnNM``h}s)Q&$oPG)xEeldwKaIXpWkVI6+zC?fqN^~yY z%DF`E6U7&c=3Z(8Vx0?c5z-f{PdidB_b5jul~u>FU<#w*0|FG0!BvDq39|TcDYbyP z$ObnoZ)01e2WbnO^gOuN5RkKE`qzc$OV5_}Y6sT7^NkyU>afQ2n}%7Op6a6A#f4_ z?j%Bs9bf(EAiJOaUHLQqNBk&xuN}SDOL=g6qQ*~|>Sgevaj77c3zA5e9dD`LusBsP zuPp*NP>_9Ih2k0R=1^gVplOTbAhqc5HK6;Cv?iw8(P=-8a$y4KS^|v#X%6&f5DLAg zJq?Knp?Xc+UEuR-*tSCts$!7;kS6B{@&wlrL1b?gl0aucK^Z)<= literal 0 HcmV?d00001 diff --git a/ai_office_orchestrator/app/adapters/base.py b/ai_office_orchestrator/app/adapters/base.py new file mode 100644 index 000000000000..3191ebdeb3bd --- /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 000000000000..df3ff33d2df2 --- /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 000000000000..7c09011a67ff --- /dev/null +++ b/ai_office_orchestrator/app/adapters/providers.py @@ -0,0 +1,74 @@ +"""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 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 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, 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 000000000000..e69de29bb2d1 diff --git a/ai_office_orchestrator/app/core/__pycache__/__init__.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60f62619fd0dd4c3d8442501d4ef826410a22b70 GIT binary patch literal 159 zcmey&%ge<81bn}KWr66&AOZ#$p^VQgK*m&tbOudEzm*I{OhDdekklejMU&ryk0@& gEe@O9{FKt1RJ$Tppm8AUib0Hz%#4hTMa)1J0ILBgE&u=k literal 0 HcmV?d00001 diff --git a/ai_office_orchestrator/app/core/__pycache__/checker.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/checker.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24e226a537f4a08c9f6cbb7cb9e1c481c6e493d3 GIT binary patch literal 694 zcmb7AO>5gg5M6y)Z5qeW&=5>qmJ&)-f|NrNC~X5h)W;s=<`jcbsOBZz*m< zFUV{S$t7u!CTS{7bz3!1Z>tTZO8Poz9o5oA30RUs=%dGNXvpN6jSw!$J~@0$$iZ#J zKG`X_E359rPN6r7y^XaU<$t?f`P4gc1C3Dj(o5wKxG`AoL<(1pJtRrHIn?U9p@Q6|bBwA2KJ6893}D3OF#w>$UjN zQO{>B4t|$mzn5@uyeM*fd5$@Mz`%}9#bVA|*Ost^meMwUjqs8DGRvPnd~J+Yz8p+y zc2=_|wXLkSHLa}wG#4&*&)-kX)y!NSo7IU)Gn0?N_c57Y^qoLO@-l+B_j1VFX~6bi8D;*4Dv~QrQIspSq^x{?Gg|+qjjU{K K^AACt_x=TjS)wHX literal 0 HcmV?d00001 diff --git a/ai_office_orchestrator/app/core/__pycache__/circuit_breaker.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/circuit_breaker.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a790a0461c0f2254e7b5ba23ceaeb7c8218a7388 GIT binary patch literal 2256 zcmb7FO-vhC5Ps`j+v|Ul64Dw45lRT#7Ti>jLr5xxpQsfCS{9=GSXnvC8a6Rr_wBkZ zAR$f_RH?|JNFcQ$hgOQ!14KOpq)NF}?WsmwtnDRIrApi=ZdEC#&g^<^Fm9#3!@Suy zZ{C|X-+Z&hP{>bUgkQeAA7=^q4L_X0m6T#LC@VxHA~Q%Rd6l#f(G?{k+wHPCSh73aY7l9P?yM1R&-^-N;&GL9+4HfxOcR!wENK1#ft7IxzA8v z+%I~fq`PFJ0nr;JG$`^QL!u94SoG7#WIza-;XakhS=H#JO5%Y+_wXG8YkK;IM#O=B zlNRGBFMEK_9MVg7P$r!@Hi zMOTwgCe&0G_Lx2`qokDyDPfo%NjDOPB5)?BE2$(6;?6q9U((^A^n^~su&iTX%`nV? z*pxP{#Im|VW6GzQltz_ULY1^+Qk4}+qwNT*});PDDm?;Y-iX@>S6nJNjp(kO| zF%!+S9;E5E5I5_qa&D~#aPL(R3*<#0vfQ)Ov)Z~YtO>h;*Pn13{+$22;HL3x{^|Tq z`@m22znuB`%x?RQLbPeUbFFi+|KVUE^2+ku(p;X8($jECZ2-E!@;?E9LT@GXHEnzf2)(ocbaT7oENmu6ST)^Dxd+KIH~`L^TXVy#&9auF10 zZVaFZTJ_L@%C%_@G2>x6fKoQ6V z@_dV3@hfxx5&iGrgvq|b)QVnYI-pc^*WspBivjR<4i2gs$cqVhO6|A>Fw|1`QUlv z$!h)AP5UhA7-B5w92R4nwS%v)7(4Q?P>02^qdUm+Rg=>rbkAxRzTQ*0xjOX*) z^M4YT`+a7gC!X*hF4o;xWI@|U?ZD5t&mVXgch_GY*4=9-#yS-!|E6;TjiH8M*v*W; hY^UN~`ZlZ~{5o=FpJf>4R}%Q!)4=pH2Lz?%^$!cYuLJ-9 literal 0 HcmV?d00001 diff --git a/ai_office_orchestrator/app/core/__pycache__/orchestrator.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/orchestrator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c64dabcfd0dc0b0cbd9936e9608d8bd06dbccf9 GIT binary patch literal 3483 zcmbVPT}&I<6~5#7u`vdlwXqE(U?5%M{JG+96_Tt33u-p0$;Qq^(GqnuYmZ@q89R5z zS%MTPFI^F-)docoY+veqO45B;o+`EKLt1U$aZH0V3VrEQ-m(E{o3sx-XY65(m8MdU z;P~Ei&pr3vbH8)Wot>5zHvwvW^XA%;laPO4$0okk*!cxC?vo@*GUv%ThB6UsJI*`K zv6Qvi?0N1SPkF1&ofpnIsWU>tq>m)|PLdR^x<=TlE!t#Bogj6MIBGKYY*W}Pm8J@+F+ml1UZEi2^;C{3&=3-eUdS4$s+lTBD@Z#5VE4&Y zLYX9?jwD0bq=Ry^Y?L$GE>KuRH>hmn=oFpQlwnneqwSyAHxI2>ZK?0H>nE@SqwL; zYR)A)qcGg)h^ySNBguA>YYgR+TqmJIlE3N%nE*15x{^-XH0z2snVx!Ay=VqgFYqQ) z959;%XrOTC_rUHG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bS#akPZkxk#|wlDmzmrj`UM#tCCpO17;_Bg)laZe5K-$jR}`uM;0@z9R4 z)yER12MZR{P~@<*Q>@?=GZV#dqWFNI-N-BiAq=dmqgd0e_jL8Si&cnXNLdUm={>-{ zAe9rb$KAVx<)g3MF8=h(K!{H;Yok99{H@N#Y17eW(`kKaKoD5a^QNlb8B*;jXKe)l z31w5&X06I=A<=>+{Q#G?kZx@PlkSfjGhL^v9}XYVk6-|w4|){XOO|1nZPL3^;@g z4Z3VT3(l++ra`y1$gg*H0icT_B`6BIGz69t)DpA8zic+lX8E%iv!X6{8K)@8RGjhL zo&X>QRItuyL&*xd(yf~STF=AzCBt;o0t}FAsxDTiQ>hts(s6AEBIa+xAb?0qsZ%rR zf?D(g6?(4iZhA09M0Sz*5Ol`V{6OS35k~Atnt<3HB7p(x07(=&#a}bOSX|=?Z$mnq zyGtv#me+J5BEMX;Gzqa0Aohe%4+X*%h#2^R;Sp{dGafY*vXFNC0!)`NL}~b-~7IV!kmlf6_m6qVzwDJ&sjZYN(+kDvMuwhpNl<-to%P=lJX+?nH^d7_ALHAFCO! z;U3&y+{dp9^}%FaNj?#O^Pq3;M{J-vT;rZ*j)k!n{SjEzBqCU@8K6Px5uSERgiYV~ zh?w_$BMAFKbd&&HU@*d}l>rofT|h})xlb*j^G~_44MA|;h5%p literal 0 HcmV?d00001 diff --git a/ai_office_orchestrator/app/core/__pycache__/task.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/task.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21c23ca50b5856c4196a6c1ed5bcc18ad50a0922 GIT binary patch literal 1030 zcma)5&ui2`6rTLt-`%curLGoAtLQ>?E7*fY#Dj>oSj2b?4AW%N#%4F`n_029LJ#)n zrFW0^zp)fbI~N5{y{+s)=*c(9RuDZH$d~u#d-GoA`;t+uRwj5&oS(n>Vi59OCl{A9 z4n{9A*e4$Gj8(E?fU#nNIZJ$Fn#>W;Y!S~|GV|J{@fNVgtc|Sm7i(|0?ZTO^ZJVkT zGRcC3389=Q=1CZgn`94roQ!-7_K8ox@CcZm0oG08+rHzOw~)yqOGlm!u3x})XPgzY z%+0DwbHp!ug$D*y{4&-QvziiAH_GjbvR^Z?b*3jOdn@jR%I!ni?aQaCBI1x!9z{Hm zs>u4d{*H$ShN_1=VuM7|hy^l*ZDn`4WCvueT~kF$d#uYTRb@)MX*fu9T&48wfF)z5 zPH7Z_kV)L*y%cFnNKm-Sdc9OK8K*r#DQJ_Fy`H8CR4|169m6<~Frld?r9xK+lt~Hk z`ap8Mt&ZFXZ=#kvn`xJK27*I}zwak0@D7V<8bxuyX$rw6$H5Gb(81Gn0?kWQ<8FT& zTx^hmo+>&BAIP_IZTI;}wZ6N0GCi}i`f=*Wo;hi@cAo8pM|SJ9apjXdY%J_N*}HLU zFTmA{4*$0HG1C8It?#0J1pxksI`vVEp zY#H_8XsO7wS!3g9saOH sEF%mp!!W**+e4R_m7k_#+!+#tk%j3nOD8kJGVTotLPq>BG0I-&7naNMrvLx| literal 0 HcmV?d00001 diff --git a/ai_office_orchestrator/app/core/checker.py b/ai_office_orchestrator/app/core/checker.py new file mode 100644 index 000000000000..0459cc6a1dfb --- /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 000000000000..396a48b5a461 --- /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/orchestrator.py b/ai_office_orchestrator/app/core/orchestrator.py new file mode 100644 index 000000000000..59fa9e44492c --- /dev/null +++ b/ai_office_orchestrator/app/core/orchestrator.py @@ -0,0 +1,50 @@ +from .checker import check_output +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): + 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 + s = score(a.profile(), 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 and 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]: + try: + out = self.adapters[name].run(task) + except Exception as e: # noqa: BLE001 + self.breakers[name].failure() + attempts.append((name, f"error: {e}")) + continue + ok, why = check_output(out) + 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}") diff --git a/ai_office_orchestrator/app/core/scoring.py b/ai_office_orchestrator/app/core/scoring.py new file mode 100644 index 000000000000..6f4309857efd --- /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 000000000000..97d9a923c2f5 --- /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/requirements.txt b/ai_office_orchestrator/requirements.txt new file mode 100644 index 000000000000..c41b78ee5794 --- /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 000000000000..e69de29bb2d1 diff --git a/ai_office_orchestrator/tests/__pycache__/__init__.cpython-313.pyc b/ai_office_orchestrator/tests/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..860eb2e3278c7266512e1390b48521a80818d65b GIT binary patch literal 156 zcmey&%ge<81bn}KWr66&AOZ#$p^VQgK*m&tbOudEzm*I{OhDdekkl<}{fzwFRQ=N8 z)FS=Vih`W{qE!9F%=rAYw9Mqx`23>ejMUTZlX-=wL5i8IvkX^+f#z$sGM#ds$APWF0Hz!2^ literal 0 HcmV?d00001 diff --git a/ai_office_orchestrator/tests/__pycache__/test_core.cpython-313.pyc b/ai_office_orchestrator/tests/__pycache__/test_core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee1cd2abf28fbd8966e6078adc107bcfa8bbb3d9 GIT binary patch literal 5490 zcmb_gU2GKB6~6PgJG-9sV)Nr4{%o)lHh>)yAa)=SV@xUFCH2@Ul~G3H_1G+|cg?+H z{vIk+sp&c;vLnTfqawws`T$iPtSS#YAT_ivd1$4qY-(#l)JUy_EcF3lqEtNfoI5+S z>t#cK#I=0(-aGf6JNJI)eCOO*iA2H#O6Ak1=jT*H{*Dc=DEZ3DU8qbGo#?_zLfv11 z3eXl$iYFv0osg;Afc?@*rf*{B|V;|w8YH6bvzp)kg)Z6o{g)dn&mj0mxcWo*Y| zqEm6iWLD>pIc8hbsp?5GmQ0UyQESLb+etGO6P(JfBu$Jb?IYAOFIW`jXs2o7oW*Qv z+8LNs-0G$@Lt&EKXR-?kZ+-j~^Np1js7#Zy1P_dgxaOP(@ej2@T+Z z(4Zcq>WCBzIr1@Bdl{iY<+gRjjwd`gP;n6c@#t3G0WnR^RQF3v>L)2^xdrM%QQdnR zGJrFA>6dkZ|A`$kjF!EA9rgHYjgXief9O8@=5S1Qf)~flRMNic1lf2ZVKL??Y|OHT z966DJBf^DZ0Y^@oqn0CO#%)Kkt|T0JD4DRG;HYKOWCErn%v6fS6h~%OYM8EtNpu~G z^&lMKBE$6?us8=>&t*of)^TRhR_n@GDnqSSGihXohm#4*$P^*dY6C`$OCtfpTE?zA zs$nG4N!u`-2%cz**NlLE)(YY}S=zB{?zJz~=B#`pG`07`_L;t$XCBmSob9~D?ri_O zD_3(Io@h(!H)Q4a!z(a_B>arCEHh=F zyXt8CRq`z`V#2ozZxUTgw?H%DqXiAr&Gr8jD$}H&yeafTt+eREZrBqOi!GqHSWkY! zj{L8w5ztj`ge5?~Zw-ZYnh5M{8TS*DXf6D3usCcnk#80Z6}*7qstx%)OLRQ#sC>Ur zLv$Iw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i5`R}J;lF5DpqL8jN&u@Npt}7R9zuR<&eG$mLak@BNgXC;= z@WE8Qd!qZprm0IaY);Nq?_1FJ^Jw$Ua|hnBbJa%|v~G83QNmaAam{SweYNSk5TyQa z7kK(G(uO|_@4SE5c%)sr_xh%;ko3p)a91Gsr%<@7Cdm0Q9;=`+Jm*(X>_mYvlO90v zLliwIeuN@{;yeocE>(J^MdG0-@HWY|fq0iZ7G-7QV@*NtFSLAGizdwfyboYOWx hA<%gAwm@Vpdu?8-TavY3^!%*n=cgY@M6Ty2^>5#rAHx6u literal 0 HcmV?d00001 diff --git a/ai_office_orchestrator/tests/test_core.py b/ai_office_orchestrator/tests/test_core.py new file mode 100644 index 000000000000..8629efad5183 --- /dev/null +++ b/ai_office_orchestrator/tests/test_core.py @@ -0,0 +1,69 @@ +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_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() From eeeccce30d25a164ad8fd50d3ed7b26eca9bf7de Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:42:51 +0000 Subject: [PATCH 02/10] Add durable metrics store, planner/classifier, CLI entry Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcmS3uz1Xhna1GGFydb --- ai_office_orchestrator/.gitignore | 2 ++ ai_office_orchestrator/app/__main__.py | 13 +++++++++ .../__pycache__/orchestrator.cpython-313.pyc | Bin 3483 -> 4389 bytes ai_office_orchestrator/app/core/metrics.py | 26 ++++++++++++++++++ .../app/core/orchestrator.py | 18 ++++++++++-- ai_office_orchestrator/app/core/planner.py | 20 ++++++++++++++ .../__pycache__/test_core.cpython-313.pyc | Bin 5490 -> 6839 bytes ai_office_orchestrator/tests/test_core.py | 16 +++++++++++ 8 files changed, 93 insertions(+), 2 deletions(-) create mode 100644 ai_office_orchestrator/.gitignore create mode 100644 ai_office_orchestrator/app/__main__.py create mode 100644 ai_office_orchestrator/app/core/metrics.py create mode 100644 ai_office_orchestrator/app/core/planner.py diff --git a/ai_office_orchestrator/.gitignore b/ai_office_orchestrator/.gitignore new file mode 100644 index 000000000000..ee2b57a1731c --- /dev/null +++ b/ai_office_orchestrator/.gitignore @@ -0,0 +1,2 @@ +metrics.db +__pycache__/ diff --git a/ai_office_orchestrator/app/__main__.py b/ai_office_orchestrator/app/__main__.py new file mode 100644 index 000000000000..a4f8cb06b37d --- /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/core/__pycache__/orchestrator.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/orchestrator.cpython-313.pyc index 1c64dabcfd0dc0b0cbd9936e9608d8bd06dbccf9..5de0cc416e2c62bc87c3fbfeba3a8e0d49367080 100644 GIT binary patch literal 4389 zcmbVPU2qfE6~4RLT}if#WaJ;&fGz(tAn*_M4+*wOYOsiZFa!xvH>S}n(#l>eugu*Q z!8FX|r5Ssgj_qU^JAH|0A26Ni#M5b~(@q~~J87Gj)X zqdK(HGt%9==bn4+-E+_R&bezvMFj|`_xbZnAJ`H4GkGzI&vn*f(7AzvD98*TjDl>? zGQjk+nDvrAH(=@KFh~3R0N*cQf%b&~YrhTKyvT!UQP5h6g0>6xc8j4C7f`MpxCQNO zj#oIs_zEABm(!0KXnlS{+v2Y@(O(ZpV-*rO9k)*60$C5ZEVc_s;B!MO92mwh= z#!=jeJevA|NF&F~fMyGwe zZVQJMaa;%Zn;<6$s2^cO7hgD6~^#pH+-PHfpvvp6x)Og^xAE4OK4 z5|cgBhICYNRPQ03v*BWszs(Riv!k_FVL0Cq7r3CM%@X7)(Ip1+LB0}UAt+q1wz1^c zE^*ivv;of^wBrIWS%L1@YO=>gpz<+U;B>_F7P$_` z-HMi9JM<_XcW4 z3L8QJVCGX`!?>Fx=0U)r{|=!fXqae&*&C+clnhyjF9ocd9J6QYIFMsRLCc^IoP`UJ zP{<=wnmA8@Lfv)&Q;YZ-L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N5!EY?15+&XP|%@HmpKa=CJWvT}>mWm+k@WhasrU9T9a3yxI|7A{7LwY==0LGddz zaEiJ{yO_HaSpFg!?F#L4inI-FbQe1yenjRX;`ywaISn-?5^7FiSomRhNFCYvOUsTc z)>U`S4HvHu-5j|wa?ASKz3tvvTyHrNK33b61hn^WHHFXBeS7ZprA7}ckwTrIO1=Ll z?I$68NBc2x6Tp+Y!GuB_De53e)ame2EZ#5AupGIVasz#i=ZdNBtDjiMkuxZ?;H{DH z%UJrLDH+&K4fh<(u#e|*cFYtS#IvgHYh3IgXt%Y-%YO6kd*$zg?%D zq0hxoOo4edUUSH9m`OEGRba_^NpuMFWUqN!|ur3Yu1r<_poe?xs$A|*H`_CSf~ zYIrrVM`Aq?-b=i(nu-#>TXg1}QpvG{NJHXj|6%<4a9`yXceZxz?GgIC0@IJCWTeQ-Uy_p`S?9sRYrHQb%*4(}vK`?_Gq(AG|9 z&OPWIySs4ry$89e_0;qOZThdRHpuMS1Toox&abXMZfSqMq2lhD&qmUB`@2u}2={y9 zV|(TM`rufv{C%&CYhA2OEY@=z!bxmKHf|{!O*F|AIQT5fy#41_OQQQZ=R0`P8;WuzJ@WVHq0~&w=K0uJGxXUR?E(D`X-*T bN$2aRHbg?m= 0: scored.append((s, name)) return [n for _, n in sorted(scored, reverse=True)] @@ -34,13 +41,16 @@ def run(self, task) -> Result: 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) + self._rec(name, task, ok, t0) if ok: self.breakers[name].success() attempts.append((name, "ok")) @@ -48,3 +58,7 @@ def run(self, task) -> Result: 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) diff --git a/ai_office_orchestrator/app/core/planner.py b/ai_office_orchestrator/app/core/planner.py new file mode 100644 index 000000000000..16074a7673c0 --- /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/tests/__pycache__/test_core.cpython-313.pyc b/ai_office_orchestrator/tests/__pycache__/test_core.cpython-313.pyc index ee1cd2abf28fbd8966e6078adc107bcfa8bbb3d9..7fc3b5230c94bbc7f2de3176c20832be6a74112b 100644 GIT binary patch delta 1396 zcmZ`(O>7%Q6rNdo*PD1ZiESvm2EjHBlr@d3Dlw=PGzvnIDbxi|ED?+pg1vFvI_og& zqJmHj;zy}KqLI}qsgTHlgSiz2iS~jx!mU{;{(6JdLgVFp}2DFk#UoVagjcpG4J8%Y^)x z$12oRzy0f6AN^+IbpM}W`r1Z$@MnQ8Y^39t=}-=2JdaRDIMMny@n*{wcTuDDiTGHP zOBK%#gUM)GV)aGp4;y1IPFHwNN`oO_iZ>NAgM;K+oOXLW(sX+>Km}I&- zTPTWMm#|Q#TOmQRPZ45=3PL^-WC>{oE(a|#c1F`)hJV#dN8z&li2_pL~g%O*e$T3gMu9{kh~fU+WHp4`N7tQ(L^&Aa4>l+ zBluD9XN=QNuTEf;Fy#@gyak8_qjuJOH1hzR824XC&xLeMLuU&ELY+dP+nr?AS*Xr8X0c4wuDGNB z@0|4grMOIQ$jWtD z>&V(_>?>_e`+8*kowl<%JhrKiUwpNrKXWN@O@59)3d`Bi=lJ_xpD%%feJ%%$-a4%& zhu~iJx|)SELhF=jG=UU*4I%Alg-EXz#j(#Wn7CHh}`)1!q419>-{J zyVkVz^rn8`;?q~~ delta 125 zcmdmP`bmrLGcPX}0}$~2`jxeTVkK Date: Mon, 16 Nov 2026 12:50:45 +0000 Subject: [PATCH 03/10] Add critic and fact-check review pass Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcmS3uz1Xhna1GGFydb --- .../__pycache__/orchestrator.cpython-313.pyc | Bin 4389 -> 4654 bytes ai_office_orchestrator/app/core/critic.py | 36 ++++++++++++++++++ .../app/core/orchestrator.py | 7 +++- .../__pycache__/test_core.cpython-313.pyc | Bin 6839 -> 8079 bytes ai_office_orchestrator/tests/test_core.py | 11 ++++++ 5 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 ai_office_orchestrator/app/core/critic.py diff --git a/ai_office_orchestrator/app/core/__pycache__/orchestrator.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/orchestrator.cpython-313.pyc index 5de0cc416e2c62bc87c3fbfeba3a8e0d49367080..639d1e09e5a76c4bee5b5af5d9ab237cc29b4aa1 100644 GIT binary patch delta 1547 zcmZ8hU1%It6ux) zSVC%YX>_l&DT~d~oVAXN@pZ~EM?=dwp~X*0sp?r;T#DS1Mb_BJ1g}Kg~NRH9+@FPZ32=_LAIqC#g_R`8BlFCL*^-{ww58F z+4_t=Afemy3K({T%OW-pXHL#VL+csfe)$39g9@z2x!QG%Yy3$^XUC+}kz2yh^l@LB zA|=k(i1Qegpy@-U&8P{PqDgXG_oY7KOG$DxK}cnJQezWlvR|K-#_9=)k}TgV>s*7f zrQv_KQk%DaiKp1FQhF56VjcudXG_`^KgTuIv=z5;m+5#;4~<%OT?j26oaY3y#k>>v zY`6SK+z1ulEft}iD}pSm$PL+6WHSgY973A+4gSq;5+vD0xjVzdA^yu8&XS)W+_Pr% zzOB3yyAXVr?q%2IXUz{9hkKN-T81A`S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@2lY6exBq^F;M#M*0`mvwc5XC-_m(oWf$dVk7%(Hc|i>d z`~Zw`h%@hkS3U2+O0DYh3_pSqWN9_RoQh(=5Npc^5@}9EiyS^7?2vNW{Or-$eacQ@ zcJ#*Q$_vtqcn&au(>9HD@ZR?z^6Zpw6{~*3+lXM4FUM*%2*M9y{Q`tFKk#6LQGJAJ ztf2278OIGuqZ*x$wa5*@TZKH@Eiy+h(IM8PuEjzc*SUk5oEk zk}0;zM|aQdzTGOG{5ieYG8X^t6j(d`W>%AKYSvs?y*V(e&5fzI#?-koJDd65%W*@t z+PzebhabW!Jb`{+LYV5Vicp2l6Ua^?yv9NFTCW6zf&%lUta@k1`y(iF!9$S{zxJk5vKDn&e)jR2v?hdHvSB%zmw7)d2)~B_eidzQEFZ_JA}XfGM=Ny={ Result: 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() diff --git a/ai_office_orchestrator/tests/__pycache__/test_core.cpython-313.pyc b/ai_office_orchestrator/tests/__pycache__/test_core.cpython-313.pyc index 7fc3b5230c94bbc7f2de3176c20832be6a74112b..614e30bed9d8bfb104be85d0214da964dbabc8af 100644 GIT binary patch delta 928 zcma))Ur19?9LMjuo9phnf6h(s47Zyhc_}mT9}Y^_LJ`EG&C(*qc0F#Bc_-)IIq+rS zgD4m}&dZV@d(-G4*h2-})0hDQiA5f2&*O)}nkh%k1?+PPCPYny6CSUTnmFe=Z{@>K)q*IgCFM_J_^o+6 zS3e}mQAJ5>VgjaS#B5Sah*~15p+1^EOc5X`nF5NMg$M?6s@G?Z)n{ zle+!F3*+<9tAyTv9fzui!6W?9+**H=9-_R)oNa7~3z>Ua#W0H7Om246fctr$fe%&V z7~hezj37UWoO4`-vrx%EF^*tX?Cfg(tMNI{;NcIkMNMar4E-X4GijtrWi7%IC|Oj} zp{$YiWKI1ej$}e~M39MsUKKh;!BOM}DN_Whk$?zysNCtY8X2Xs*F;3gOvk8n2u?v+ zgAbS~$VG=!fs8IUek2I(64fhUqeL)F#rGn delta 275 zcmeCT-)_qHnU|M~0SG*P{mN40p2#P`^n_ue#uJuwMor$$R*XA26*bw4Kq`vdKm;3z zPzMnlAi^C;Xl@qaUdX~2v3VQ+NhZdO$qhn|jGCJd36(Pn_<_^}fru0kk-gbdB%g_~ zX!1@mGoB)#$Sua)Ta58VS(|^09cL7(2dM$sqRCVw31Zhzz9KQpqXxum1`&E7LIFg` zfe2|3kq;w0fQ(`uAkoI~iHV)n?yC?ps|iFQNR6h@WN*0zjQNv4%E@x|00kI9>Z2!1 O$VYO0W#DCmC Date: Mon, 16 Nov 2026 12:50:59 +0000 Subject: [PATCH 04/10] Fix critic: do not reject short valid answers Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcmS3uz1Xhna1GGFydb --- ai_office_orchestrator/app/core/critic.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/ai_office_orchestrator/app/core/critic.py b/ai_office_orchestrator/app/core/critic.py index ba3e4e2274d7..e0161a517182 100644 --- a/ai_office_orchestrator/app/core/critic.py +++ b/ai_office_orchestrator/app/core/critic.py @@ -9,8 +9,6 @@ def heuristic_review(task, output: str): text = str(output).strip() if _REFUSAL.search(text[:200]): return False, "looks like a refusal" - if len(text) < 3: - return False, "too short" return True, "ok" From dd8968fa70ea5134a10631ecee6aa2eb507847fc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:54:11 +0000 Subject: [PATCH 05/10] Remove committed __pycache__ files Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcmS3uz1Xhna1GGFydb --- .../app/__pycache__/__init__.cpython-313.pyc | Bin 154 -> 0 bytes .../__pycache__/__init__.cpython-313.pyc | Bin 163 -> 0 bytes .../adapters/__pycache__/base.cpython-313.pyc | Bin 1867 -> 0 bytes .../core/__pycache__/__init__.cpython-313.pyc | Bin 159 -> 0 bytes .../app/core/__pycache__/checker.cpython-313.pyc | Bin 694 -> 0 bytes .../__pycache__/circuit_breaker.cpython-313.pyc | Bin 2256 -> 0 bytes .../__pycache__/orchestrator.cpython-313.pyc | Bin 4654 -> 0 bytes .../app/core/__pycache__/scoring.cpython-313.pyc | Bin 968 -> 0 bytes .../app/core/__pycache__/task.cpython-313.pyc | Bin 1030 -> 0 bytes .../tests/__pycache__/__init__.cpython-313.pyc | Bin 156 -> 0 bytes .../tests/__pycache__/test_core.cpython-313.pyc | Bin 8079 -> 0 bytes 11 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ai_office_orchestrator/app/__pycache__/__init__.cpython-313.pyc delete mode 100644 ai_office_orchestrator/app/adapters/__pycache__/__init__.cpython-313.pyc delete mode 100644 ai_office_orchestrator/app/adapters/__pycache__/base.cpython-313.pyc delete mode 100644 ai_office_orchestrator/app/core/__pycache__/__init__.cpython-313.pyc delete mode 100644 ai_office_orchestrator/app/core/__pycache__/checker.cpython-313.pyc delete mode 100644 ai_office_orchestrator/app/core/__pycache__/circuit_breaker.cpython-313.pyc delete mode 100644 ai_office_orchestrator/app/core/__pycache__/orchestrator.cpython-313.pyc delete mode 100644 ai_office_orchestrator/app/core/__pycache__/scoring.cpython-313.pyc delete mode 100644 ai_office_orchestrator/app/core/__pycache__/task.cpython-313.pyc delete mode 100644 ai_office_orchestrator/tests/__pycache__/__init__.cpython-313.pyc delete mode 100644 ai_office_orchestrator/tests/__pycache__/test_core.cpython-313.pyc diff --git a/ai_office_orchestrator/app/__pycache__/__init__.cpython-313.pyc b/ai_office_orchestrator/app/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index 91c18de68f98c3dde0f07a8e16a2e04c2f55682d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 154 zcmey&%ge<81bn}KWr66&AOZ#$p^VQgK*m&tbOudEzm*I{OhDdekklejMUKEC9tHCQ$$Y diff --git a/ai_office_orchestrator/app/adapters/__pycache__/__init__.cpython-313.pyc b/ai_office_orchestrator/app/adapters/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index 93586698776327a05add25c0c36b66cf193997e7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 163 zcmey&%ge<81bn}KWr66&AOZ#$p^VQgK*m&tbOudEzm*I{OhDdekklejMUU_%qDt&B^OT8VHY;x?@sq|%}YRq=ssPB>jH_5d5!yUyD+ z3O)JMa*m1uC#0Ujtv&T$NKZBLA!r))(i1m?BSp%o@2%Hhqs-ykH*em|y!pO2v)!?= z5r!@C?%m@JnX&(<({E~EbU#O9muXCszGuL$usqY`EYm_2sTAtPfb4q}^r|IXhZ=;| zr9$|G%yN~m-=x6kX3*GW6$X;VK-MG(X)-A5p@JgDADFId+Uwr}uW{Qm4eLa~=tEX6 zs3NNCwo&K0E=F{{?$nwV*>PQe(lo4KB&q9bCb*tu+T3<C%(;`_0qgu2Qzawk0EPJfLm^OmG1p1Qb8})rDTw{DaUKkUj3z+CPy{u27xPnk9 zb-{cNgt}?kHCIIH9NDS5)xJs?$mm3raQ8QaUABVQYs-Pw{XTv3>>*pG8JC(S^($jJ za%l*=rNCuN52a57yLN@Kl~_Mkli$B?g3ZaLAX|>JXILRrh6$YZ(~Y2ta=@Q7O)RAx zx3^4i>^jy|Zp#4EShe_9Ijkw!aYcBYdl(=h2>K@97AgvEHhfVFvQS)ZtqFC@u$tVZ zgXeNEh95CfJ+D$RHNf)hg+GCD?mR+^y-rO$k3Ea+%^cj?zx6`yq;9@S-9Ad)?xf~+ z)PIwi*At(#uRnNM``h}s)Q&$oPG)xEeldwKaIXpWkVI6+zC?fqN^~yY z%DF`E6U7&c=3Z(8Vx0?c5z-f{PdidB_b5jul~u>FU<#w*0|FG0!BvDq39|TcDYbyP z$ObnoZ)01e2WbnO^gOuN5RkKE`qzc$OV5_}Y6sT7^NkyU>afQ2n}%7Op6a6A#f4_ z?j%Bs9bf(EAiJOaUHLQqNBk&xuN}SDOL=g6qQ*~|>Sgevaj77c3zA5e9dD`LusBsP zuPp*NP>_9Ih2k0R=1^gVplOTbAhqc5HK6;Cv?iw8(P=-8a$y4KS^|v#X%6&f5DLAg zJq?Knp?Xc+UEuR-*tSCts$!7;kS6B{@&wlrL1b?gl0aucK^Z)<= diff --git a/ai_office_orchestrator/app/core/__pycache__/__init__.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index 60f62619fd0dd4c3d8442501d4ef826410a22b70..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 159 zcmey&%ge<81bn}KWr66&AOZ#$p^VQgK*m&tbOudEzm*I{OhDdekklejMU&ryk0@& gEe@O9{FKt1RJ$Tppm8AUib0Hz%#4hTMa)1J0ILBgE&u=k diff --git a/ai_office_orchestrator/app/core/__pycache__/checker.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/checker.cpython-313.pyc deleted file mode 100644 index 24e226a537f4a08c9f6cbb7cb9e1c481c6e493d3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 694 zcmb7AO>5gg5M6y)Z5qeW&=5>qmJ&)-f|NrNC~X5h)W;s=<`jcbsOBZz*m< zFUV{S$t7u!CTS{7bz3!1Z>tTZO8Poz9o5oA30RUs=%dGNXvpN6jSw!$J~@0$$iZ#J zKG`X_E359rPN6r7y^XaU<$t?f`P4gc1C3Dj(o5wKxG`AoL<(1pJtRrHIn?U9p@Q6|bBwA2KJ6893}D3OF#w>$UjN zQO{>B4t|$mzn5@uyeM*fd5$@Mz`%}9#bVA|*Ost^meMwUjqs8DGRvPnd~J+Yz8p+y zc2=_|wXLkSHLa}wG#4&*&)-kX)y!NSo7IU)Gn0?N_c57Y^qoLO@-l+B_j1VFX~6bi8D;*4Dv~QrQIspSq^x{?Gg|+qjjU{K K^AACt_x=TjS)wHX diff --git a/ai_office_orchestrator/app/core/__pycache__/circuit_breaker.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/circuit_breaker.cpython-313.pyc deleted file mode 100644 index a790a0461c0f2254e7b5ba23ceaeb7c8218a7388..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2256 zcmb7FO-vhC5Ps`j+v|Ul64Dw45lRT#7Ti>jLr5xxpQsfCS{9=GSXnvC8a6Rr_wBkZ zAR$f_RH?|JNFcQ$hgOQ!14KOpq)NF}?WsmwtnDRIrApi=ZdEC#&g^<^Fm9#3!@Suy zZ{C|X-+Z&hP{>bUgkQeAA7=^q4L_X0m6T#LC@VxHA~Q%Rd6l#f(G?{k+wHPCSh73aY7l9P?yM1R&-^-N;&GL9+4HfxOcR!wENK1#ft7IxzA8v z+%I~fq`PFJ0nr;JG$`^QL!u94SoG7#WIza-;XakhS=H#JO5%Y+_wXG8YkK;IM#O=B zlNRGBFMEK_9MVg7P$r!@Hi zMOTwgCe&0G_Lx2`qokDyDPfo%NjDOPB5)?BE2$(6;?6q9U((^A^n^~su&iTX%`nV? z*pxP{#Im|VW6GzQltz_ULY1^+Qk4}+qwNT*});PDDm?;Y-iX@>S6nJNjp(kO| zF%!+S9;E5E5I5_qa&D~#aPL(R3*<#0vfQ)Ov)Z~YtO>h;*Pn13{+$22;HL3x{^|Tq z`@m22znuB`%x?RQLbPeUbFFi+|KVUE^2+ku(p;X8($jECZ2-E!@;?E9LT@GXHEnzf2)(ocbaT7oENmu6ST)^Dxd+KIH~`L^TXVy#&9auF10 zZVaFZTJ_L@%C%_@G2>x6fKoQ6V z@_dV3@hfxx5&iGrgvq|b)QVnYI-pc^*WspBivjR<4i2gs$cqVhO6|A>Fw|1`QUlv z$!h)AP5UhA7-B5w92R4nwS%v)7(4Q?P>02^qdUm+Rg=>rbkAxRzTQ*0xjOX*) z^M4YT`+a7gC!X*hF4o;xWI@|U?ZD5t&mVXgch_GY*4=9-#yS-!|E6;TjiH8M*v*W; hY^UN~`ZlZ~{5o=FpJf>4R}%Q!)4=pH2Lz?%^$!cYuLJ-9 diff --git a/ai_office_orchestrator/app/core/__pycache__/orchestrator.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/orchestrator.cpython-313.pyc deleted file mode 100644 index 639d1e09e5a76c4bee5b5af5d9ab237cc29b4aa1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4654 zcmbUlTTmO<_3mm{D}k_tB|u;Y#KRB8<`E3e1e^yL`~c&`lI7CiM%_p&SX->{-IZPRG~8LP?kn+eVoY zma+lFxl!8)M>zxMNBI#uwHvs7R2Xqkhk*;D&XEdQ5g>ljLc)#)5_X=i?6sNlsmq{N z0JXB0EzqhanV{fy?E=E&nZ6>Wj-%h2=vUCNo9YDA9uSWeZbsHNyI zr78LV6?Kc84)VGq8dbz;DH_!)qS5J8Je@?`6^&j>i^;->I~q;MRMnEQA}J{tu8Brf zP1NLARMa#ozns=2H5#QZ+z9*;eXw&XH7#|fRf%>=S7(xNfKE}4rV&(Ug8CgI>Jt%Im2+dptefgRjRfJJ3#CMyyer!Vgh_DumghRho3-mgN&b3 z*$7EmqXcm4ipcnL$%07`5@EdLoS?E@L}k6?gqx7ml@Q7*gNP7i$EpdbBmv-51dzvB zEM+pl0{(*xTMOweOaf`Ok4UrhM#cll;`)=YmbqS{1iQtY4hp)%G*yY}E-)!MrbQEC zOjC7XTEecXb7(cXLyU_vnnYFI@v>>ks_vQ=ucF0B(=(bHbm*KaB@?s}wnhWc=24fqz-AYYGotE%Z=e9wi$pMBS&=og%F+w#u*jfVqJ9&a*T|m^99nbipX1)B zTF~y*?a$XWzTx`lU{B89`{NUtOK;b{Rhy~)e*LWzS${7weRO0f=O6yniB)6hou*uK z_ucyLU&8P(4(E68|G-iI#b-RJKm3L6A6C&$->Mzh!~J^Kz~fx3c-KJ2Z5vk70Mr|# zlPF*%At07R2)W9@x;wCw_XtUYgqa?gU9^KO_J|FyGgNAyg+WWk{z5+vQpSQ{hg`_H zHQ&N4ZiR<+@K|MFNfDnVq>DuOVJ6JrH&j)|2wfbpLg6s8y}S@!QW=at5%Q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N#OGj O$CJz{<}-q=A@JX>29ZVp diff --git a/ai_office_orchestrator/app/core/__pycache__/scoring.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/scoring.cpython-313.pyc deleted file mode 100644 index d5a4362d6895b5e54669a3d96a43823314b3cf22..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 968 zcmZuvOH30%7@qAuX(^;@g z4Z3VT3(l++ra`y1$gg*H0icT_B`6BIGz69t)DpA8zic+lX8E%iv!X6{8K)@8RGjhL zo&X>QRItuyL&*xd(yf~STF=AzCBt;o0t}FAsxDTiQ>hts(s6AEBIa+xAb?0qsZ%rR zf?D(g6?(4iZhA09M0Sz*5Ol`V{6OS35k~Atnt<3HB7p(x07(=&#a}bOSX|=?Z$mnq zyGtv#me+J5BEMX;Gzqa0Aohe%4+X*%h#2^R;Sp{dGafY*vXFNC0!)`NL}~b-~7IV!kmlf6_m6qVzwDJ&sjZYN(+kDvMuwhpNl<-to%P=lJX+?nH^d7_ALHAFCO! z;U3&y+{dp9^}%FaNj?#O^Pq3;M{J-vT;rZ*j)k!n{SjEzBqCU@8K6Px5uSERgiYV~ zh?w_$BMAFKbd&&HU@*d}l>rofT|h})xlb*j^G~_44MA|;h5%p diff --git a/ai_office_orchestrator/app/core/__pycache__/task.cpython-313.pyc b/ai_office_orchestrator/app/core/__pycache__/task.cpython-313.pyc deleted file mode 100644 index 21c23ca50b5856c4196a6c1ed5bcc18ad50a0922..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1030 zcma)5&ui2`6rTLt-`%curLGoAtLQ>?E7*fY#Dj>oSj2b?4AW%N#%4F`n_029LJ#)n zrFW0^zp)fbI~N5{y{+s)=*c(9RuDZH$d~u#d-GoA`;t+uRwj5&oS(n>Vi59OCl{A9 z4n{9A*e4$Gj8(E?fU#nNIZJ$Fn#>W;Y!S~|GV|J{@fNVgtc|Sm7i(|0?ZTO^ZJVkT zGRcC3389=Q=1CZgn`94roQ!-7_K8ox@CcZm0oG08+rHzOw~)yqOGlm!u3x})XPgzY z%+0DwbHp!ug$D*y{4&-QvziiAH_GjbvR^Z?b*3jOdn@jR%I!ni?aQaCBI1x!9z{Hm zs>u4d{*H$ShN_1=VuM7|hy^l*ZDn`4WCvueT~kF$d#uYTRb@)MX*fu9T&48wfF)z5 zPH7Z_kV)L*y%cFnNKm-Sdc9OK8K*r#DQJ_Fy`H8CR4|169m6<~Frld?r9xK+lt~Hk z`ap8Mt&ZFXZ=#kvn`xJK27*I}zwak0@D7V<8bxuyX$rw6$H5Gb(81Gn0?kWQ<8FT& zTx^hmo+>&BAIP_IZTI;}wZ6N0GCi}i`f=*Wo;hi@cAo8pM|SJ9apjXdY%J_N*}HLU zFTmA{4*$0HG1C8It?#0J1pxksI`vVEp zY#H_8XsO7wS!3g9saOH sEF%mp!!W**+e4R_m7k_#+!+#tk%j3nOD8kJGVTotLPq>BG0I-&7naNMrvLx| diff --git a/ai_office_orchestrator/tests/__pycache__/__init__.cpython-313.pyc b/ai_office_orchestrator/tests/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index 860eb2e3278c7266512e1390b48521a80818d65b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 156 zcmey&%ge<81bn}KWr66&AOZ#$p^VQgK*m&tbOudEzm*I{OhDdekkl<}{fzwFRQ=N8 z)FS=Vih`W{qE!9F%=rAYw9Mqx`23>ejMUTZlX-=wL5i8IvkX^+f#z$sGM#ds$APWF0Hz!2^ diff --git a/ai_office_orchestrator/tests/__pycache__/test_core.cpython-313.pyc b/ai_office_orchestrator/tests/__pycache__/test_core.cpython-313.pyc deleted file mode 100644 index 614e30bed9d8bfb104be85d0214da964dbabc8af..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8079 zcmdT}U2GKB6~6PcyW{n&7n>h@&EEoc!V+x9!3InSV2lajXQ3WjB{9uty&l^O>s{y0 zE(RW26jkZENrWSX#H2{EsysMV9;_-4u7p(5_JN01V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-m>9d=6%m!Mfe~=CAnpt^A zdg0Lsj0$1~KLQmbr+Ehd7!nDId&lGz(KZi8>TtHAf^Gxn1It?#cdkE}jmI$?DH?}U zbZp?_C3zrrA($G9>A}AAAf|u&fe#I7K#17!EhOYw!ied|^mSO2g##;P$QlZAEarj0 zUc?AKPLXyGOom#S+u_)+F`<05JrcA;)U?N zis17n*!BjBQcy|p0SbgBmZ3qY^tkpttP)%;=Ir?Re}Y0UetidxK`L_bG)`t|2de-7 zX@KgNf>A*CWGVm}nC!&ep3p}%TEtIi7`A|(1W|b6-@s6TY6EE< z$O2?<2M0B(=jcKxx1}Z`Jhto0I5$FrMG)-bW@uqTXD0|?C-)BbP6IiE^ zS3fD0ljGc&szbgDp##%yrTkhb736Xu3YoI)>$dloJT?|4>ST*guISRvYl*ZL9HiQ4 zu%)%WNPU+AFIo?RTlHj`MzuXbs*NORD#SF3JX3}rj^OtpP*OCd=W;)gOu%!887eSJ zlr(XZQ;9(`w=dSmgg8o z)AWw4f7gvwGtt{G_GR0m4so37&&oRrF@N>7)z?##ho?GbH$DppH6PfM4eXiexFa3- zc1U^~zxo{%r636-7)60lp;v%FNJ7r`P!e42oH;*s2(6?oa51Db{5Xa?W>jL(j+noT z>WzKyBPmOmo0;(%C!$-2R<+Okanw8-uXY~i{~Twk4G&p{&*^|a5SeEJ)T|*f1>jPQMKz?o=5IUu=m*dn@la2K_)6e7?h8`(1@Ye}d+(7Qe$CFuWdb)}o#KcnXD-bOfdx_i*@@Rr{Pg6q+sCy`)XWFA eWdqxm3EV6PC9a(tubHphoUPpakl-EL%6|hGPA*UY From 3a2911b7ce2aadecf9571148081c16935fca6859 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:55:01 +0000 Subject: [PATCH 06/10] Remove AI Office Orchestrator (cancelled) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcmS3uz1Xhna1GGFydb --- ai_office_orchestrator/.env.example | 6 -- ai_office_orchestrator/.gitignore | 2 - ai_office_orchestrator/README.md | 8 -- ai_office_orchestrator/app/__init__.py | 0 ai_office_orchestrator/app/__main__.py | 13 --- .../app/adapters/__init__.py | 0 ai_office_orchestrator/app/adapters/base.py | 27 ------ .../app/adapters/factory.py | 5 - .../app/adapters/providers.py | 74 -------------- ai_office_orchestrator/app/core/__init__.py | 0 ai_office_orchestrator/app/core/checker.py | 7 -- .../app/core/circuit_breaker.py | 26 ----- ai_office_orchestrator/app/core/critic.py | 34 ------- ai_office_orchestrator/app/core/metrics.py | 26 ----- .../app/core/orchestrator.py | 69 ------------- ai_office_orchestrator/app/core/planner.py | 20 ---- ai_office_orchestrator/app/core/scoring.py | 12 --- ai_office_orchestrator/app/core/task.py | 17 ---- ai_office_orchestrator/requirements.txt | 3 - ai_office_orchestrator/tests/__init__.py | 0 ai_office_orchestrator/tests/test_core.py | 96 ------------------- 21 files changed, 445 deletions(-) delete mode 100644 ai_office_orchestrator/.env.example delete mode 100644 ai_office_orchestrator/.gitignore delete mode 100644 ai_office_orchestrator/README.md delete mode 100644 ai_office_orchestrator/app/__init__.py delete mode 100644 ai_office_orchestrator/app/__main__.py delete mode 100644 ai_office_orchestrator/app/adapters/__init__.py delete mode 100644 ai_office_orchestrator/app/adapters/base.py delete mode 100644 ai_office_orchestrator/app/adapters/factory.py delete mode 100644 ai_office_orchestrator/app/adapters/providers.py delete mode 100644 ai_office_orchestrator/app/core/__init__.py delete mode 100644 ai_office_orchestrator/app/core/checker.py delete mode 100644 ai_office_orchestrator/app/core/circuit_breaker.py delete mode 100644 ai_office_orchestrator/app/core/critic.py delete mode 100644 ai_office_orchestrator/app/core/metrics.py delete mode 100644 ai_office_orchestrator/app/core/orchestrator.py delete mode 100644 ai_office_orchestrator/app/core/planner.py delete mode 100644 ai_office_orchestrator/app/core/scoring.py delete mode 100644 ai_office_orchestrator/app/core/task.py delete mode 100644 ai_office_orchestrator/requirements.txt delete mode 100644 ai_office_orchestrator/tests/__init__.py delete mode 100644 ai_office_orchestrator/tests/test_core.py diff --git a/ai_office_orchestrator/.env.example b/ai_office_orchestrator/.env.example deleted file mode 100644 index 50c34ee384d0..000000000000 --- a/ai_office_orchestrator/.env.example +++ /dev/null @@ -1,6 +0,0 @@ -# Set real values in your environment, never commit them. -OPENAI_API_KEY= -GEMINI_API_KEY= -ANTHROPIC_API_KEY= -MODEL_API_KEY= -CANVA_ACCESS_TOKEN= diff --git a/ai_office_orchestrator/.gitignore b/ai_office_orchestrator/.gitignore deleted file mode 100644 index ee2b57a1731c..000000000000 --- a/ai_office_orchestrator/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -metrics.db -__pycache__/ diff --git a/ai_office_orchestrator/README.md b/ai_office_orchestrator/README.md deleted file mode 100644 index 550ac0d9a02b..000000000000 --- a/ai_office_orchestrator/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# 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. -- Credentials come from environment variables only (see `.env.example`). -- Adapters are unverified against live APIs. Run tests: `python -m unittest discover -s tests -t .` diff --git a/ai_office_orchestrator/app/__init__.py b/ai_office_orchestrator/app/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ai_office_orchestrator/app/__main__.py b/ai_office_orchestrator/app/__main__.py deleted file mode 100644 index a4f8cb06b37d..000000000000 --- a/ai_office_orchestrator/app/__main__.py +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ai_office_orchestrator/app/adapters/base.py b/ai_office_orchestrator/app/adapters/base.py deleted file mode 100644 index 3191ebdeb3bd..000000000000 --- a/ai_office_orchestrator/app/adapters/base.py +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index df3ff33d2df2..000000000000 --- a/ai_office_orchestrator/app/adapters/factory.py +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index 7c09011a67ff..000000000000 --- a/ai_office_orchestrator/app/adapters/providers.py +++ /dev/null @@ -1,74 +0,0 @@ -"""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 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 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, MetaAdapter, CanvaAdapter] diff --git a/ai_office_orchestrator/app/core/__init__.py b/ai_office_orchestrator/app/core/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ai_office_orchestrator/app/core/checker.py b/ai_office_orchestrator/app/core/checker.py deleted file mode 100644 index 0459cc6a1dfb..000000000000 --- a/ai_office_orchestrator/app/core/checker.py +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 396a48b5a461..000000000000 --- a/ai_office_orchestrator/app/core/circuit_breaker.py +++ /dev/null @@ -1,26 +0,0 @@ -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/critic.py b/ai_office_orchestrator/app/core/critic.py deleted file mode 100644 index e0161a517182..000000000000 --- a/ai_office_orchestrator/app/core/critic.py +++ /dev/null @@ -1,34 +0,0 @@ -"""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 deleted file mode 100644 index e47c2e46872c..000000000000 --- a/ai_office_orchestrator/app/core/metrics.py +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 803c61335c3f..000000000000 --- a/ai_office_orchestrator/app/core/orchestrator.py +++ /dev/null @@ -1,69 +0,0 @@ -import time - -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): - 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 and 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) diff --git a/ai_office_orchestrator/app/core/planner.py b/ai_office_orchestrator/app/core/planner.py deleted file mode 100644 index 16074a7673c0..000000000000 --- a/ai_office_orchestrator/app/core/planner.py +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index 6f4309857efd..000000000000 --- a/ai_office_orchestrator/app/core/scoring.py +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 97d9a923c2f5..000000000000 --- a/ai_office_orchestrator/app/core/task.py +++ /dev/null @@ -1,17 +0,0 @@ -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/requirements.txt b/ai_office_orchestrator/requirements.txt deleted file mode 100644 index c41b78ee5794..000000000000 --- a/ai_office_orchestrator/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -openai -google-genai -anthropic diff --git a/ai_office_orchestrator/tests/__init__.py b/ai_office_orchestrator/tests/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ai_office_orchestrator/tests/test_core.py b/ai_office_orchestrator/tests/test_core.py deleted file mode 100644 index 6787383c99de..000000000000 --- a/ai_office_orchestrator/tests/test_core.py +++ /dev/null @@ -1,96 +0,0 @@ -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_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") From 747e74d018a96f1b32e2ea775380afcaacc7827f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:03:48 +0000 Subject: [PATCH 07/10] Restore AI Office Orchestrator Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcmS3uz1Xhna1GGFydb --- ai_office_orchestrator/.env.example | 6 ++ ai_office_orchestrator/.gitignore | 2 + ai_office_orchestrator/README.md | 8 ++ ai_office_orchestrator/app/__init__.py | 0 ai_office_orchestrator/app/__main__.py | 13 +++ .../app/adapters/__init__.py | 0 ai_office_orchestrator/app/adapters/base.py | 27 ++++++ .../app/adapters/factory.py | 5 + .../app/adapters/providers.py | 74 ++++++++++++++ ai_office_orchestrator/app/core/__init__.py | 0 ai_office_orchestrator/app/core/checker.py | 7 ++ .../app/core/circuit_breaker.py | 26 +++++ ai_office_orchestrator/app/core/critic.py | 34 +++++++ ai_office_orchestrator/app/core/metrics.py | 26 +++++ .../app/core/orchestrator.py | 69 +++++++++++++ ai_office_orchestrator/app/core/planner.py | 20 ++++ ai_office_orchestrator/app/core/scoring.py | 12 +++ ai_office_orchestrator/app/core/task.py | 17 ++++ ai_office_orchestrator/requirements.txt | 3 + ai_office_orchestrator/tests/__init__.py | 0 ai_office_orchestrator/tests/test_core.py | 96 +++++++++++++++++++ 21 files changed, 445 insertions(+) create mode 100644 ai_office_orchestrator/.env.example create mode 100644 ai_office_orchestrator/.gitignore create mode 100644 ai_office_orchestrator/README.md create mode 100644 ai_office_orchestrator/app/__init__.py create mode 100644 ai_office_orchestrator/app/__main__.py create mode 100644 ai_office_orchestrator/app/adapters/__init__.py create mode 100644 ai_office_orchestrator/app/adapters/base.py create mode 100644 ai_office_orchestrator/app/adapters/factory.py create mode 100644 ai_office_orchestrator/app/adapters/providers.py create mode 100644 ai_office_orchestrator/app/core/__init__.py create mode 100644 ai_office_orchestrator/app/core/checker.py create mode 100644 ai_office_orchestrator/app/core/circuit_breaker.py create mode 100644 ai_office_orchestrator/app/core/critic.py create mode 100644 ai_office_orchestrator/app/core/metrics.py create mode 100644 ai_office_orchestrator/app/core/orchestrator.py create mode 100644 ai_office_orchestrator/app/core/planner.py create mode 100644 ai_office_orchestrator/app/core/scoring.py create mode 100644 ai_office_orchestrator/app/core/task.py create mode 100644 ai_office_orchestrator/requirements.txt create mode 100644 ai_office_orchestrator/tests/__init__.py create mode 100644 ai_office_orchestrator/tests/test_core.py diff --git a/ai_office_orchestrator/.env.example b/ai_office_orchestrator/.env.example new file mode 100644 index 000000000000..50c34ee384d0 --- /dev/null +++ b/ai_office_orchestrator/.env.example @@ -0,0 +1,6 @@ +# Set real values in your environment, never commit them. +OPENAI_API_KEY= +GEMINI_API_KEY= +ANTHROPIC_API_KEY= +MODEL_API_KEY= +CANVA_ACCESS_TOKEN= diff --git a/ai_office_orchestrator/.gitignore b/ai_office_orchestrator/.gitignore new file mode 100644 index 000000000000..ee2b57a1731c --- /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 000000000000..550ac0d9a02b --- /dev/null +++ b/ai_office_orchestrator/README.md @@ -0,0 +1,8 @@ +# 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. +- Credentials come from environment variables only (see `.env.example`). +- Adapters are unverified against live APIs. Run tests: `python -m unittest discover -s tests -t .` diff --git a/ai_office_orchestrator/app/__init__.py b/ai_office_orchestrator/app/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/ai_office_orchestrator/app/__main__.py b/ai_office_orchestrator/app/__main__.py new file mode 100644 index 000000000000..a4f8cb06b37d --- /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 000000000000..e69de29bb2d1 diff --git a/ai_office_orchestrator/app/adapters/base.py b/ai_office_orchestrator/app/adapters/base.py new file mode 100644 index 000000000000..3191ebdeb3bd --- /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 000000000000..df3ff33d2df2 --- /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 000000000000..7c09011a67ff --- /dev/null +++ b/ai_office_orchestrator/app/adapters/providers.py @@ -0,0 +1,74 @@ +"""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 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 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, 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 000000000000..e69de29bb2d1 diff --git a/ai_office_orchestrator/app/core/checker.py b/ai_office_orchestrator/app/core/checker.py new file mode 100644 index 000000000000..0459cc6a1dfb --- /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 000000000000..396a48b5a461 --- /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/critic.py b/ai_office_orchestrator/app/core/critic.py new file mode 100644 index 000000000000..e0161a517182 --- /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 000000000000..e47c2e46872c --- /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 000000000000..803c61335c3f --- /dev/null +++ b/ai_office_orchestrator/app/core/orchestrator.py @@ -0,0 +1,69 @@ +import time + +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): + 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 and 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) diff --git a/ai_office_orchestrator/app/core/planner.py b/ai_office_orchestrator/app/core/planner.py new file mode 100644 index 000000000000..16074a7673c0 --- /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 000000000000..6f4309857efd --- /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 000000000000..97d9a923c2f5 --- /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/requirements.txt b/ai_office_orchestrator/requirements.txt new file mode 100644 index 000000000000..c41b78ee5794 --- /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 000000000000..e69de29bb2d1 diff --git a/ai_office_orchestrator/tests/test_core.py b/ai_office_orchestrator/tests/test_core.py new file mode 100644 index 000000000000..6787383c99de --- /dev/null +++ b/ai_office_orchestrator/tests/test_core.py @@ -0,0 +1,96 @@ +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_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") From 5d63ca32716abae0e41502ff8dc8e7f5918c709f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:31:42 +0000 Subject: [PATCH 08/10] Add parallel ensemble mode with pluggable selection Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcmS3uz1Xhna1GGFydb --- .../app/core/orchestrator.py | 37 +++++++++++++++++++ ai_office_orchestrator/tests/test_core.py | 19 ++++++++++ 2 files changed, 56 insertions(+) diff --git a/ai_office_orchestrator/app/core/orchestrator.py b/ai_office_orchestrator/app/core/orchestrator.py index 803c61335c3f..ed534490cc95 100644 --- a/ai_office_orchestrator/app/core/orchestrator.py +++ b/ai_office_orchestrator/app/core/orchestrator.py @@ -1,4 +1,5 @@ import time +from concurrent.futures import ThreadPoolExecutor from .checker import check_output from .critic import review @@ -67,3 +68,39 @@ def run(self, task) -> Result: 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/tests/test_core.py b/ai_office_orchestrator/tests/test_core.py index 6787383c99de..96ff40be80fe 100644 --- a/ai_office_orchestrator/tests/test_core.py +++ b/ai_office_orchestrator/tests/test_core.py @@ -94,3 +94,22 @@ 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)) From 2a2e5183119e57ed6492cb5e2dd2f35f5c145708 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:40:35 +0000 Subject: [PATCH 09/10] Add Grok (xAI) adapter, test, and provider reference Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcnLLeaMa9S2vGmLSFV --- ai_office_orchestrator/.env.example | 2 ++ ai_office_orchestrator/README.md | 1 + .../app/adapters/providers.py | 20 ++++++++++++++++++- .../docs_provider_reference.md | 15 ++++++++++++++ ai_office_orchestrator/tests/test_core.py | 13 ++++++++++++ 5 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 ai_office_orchestrator/docs_provider_reference.md diff --git a/ai_office_orchestrator/.env.example b/ai_office_orchestrator/.env.example index 50c34ee384d0..f96ca595633f 100644 --- a/ai_office_orchestrator/.env.example +++ b/ai_office_orchestrator/.env.example @@ -4,3 +4,5 @@ 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/README.md b/ai_office_orchestrator/README.md index 550ac0d9a02b..32721af4050c 100644 --- a/ai_office_orchestrator/README.md +++ b/ai_office_orchestrator/README.md @@ -6,3 +6,4 @@ Task -> score providers (health, quality, success, speed, cost) -> circuit break - Side-effect tasks (email, publish, calendar) need `approved=True` and never fail over. - 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/adapters/providers.py b/ai_office_orchestrator/app/adapters/providers.py index 7c09011a67ff..1ec7c2cc4a2a 100644 --- a/ai_office_orchestrator/app/adapters/providers.py +++ b/ai_office_orchestrator/app/adapters/providers.py @@ -1,6 +1,7 @@ """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 @@ -42,6 +43,23 @@ def run(self, task): 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",) @@ -71,4 +89,4 @@ def run(self, task): raise NotImplementedError("Canva requires an OAuth flow; not implemented") -ALL = [OpenAIAdapter, GeminiAdapter, ClaudeAdapter, MetaAdapter, CanvaAdapter] +ALL = [OpenAIAdapter, GeminiAdapter, ClaudeAdapter, GrokAdapter, MetaAdapter, CanvaAdapter] diff --git a/ai_office_orchestrator/docs_provider_reference.md b/ai_office_orchestrator/docs_provider_reference.md new file mode 100644 index 000000000000..5eea44a2d5c1 --- /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/tests/test_core.py b/ai_office_orchestrator/tests/test_core.py index 96ff40be80fe..db522734fd72 100644 --- a/ai_office_orchestrator/tests/test_core.py +++ b/ai_office_orchestrator/tests/test_core.py @@ -32,6 +32,19 @@ def test_missing_key(self): 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_failover(self): a, b = Fake("a", exc=RuntimeError("down"), q=0.9), Fake("b", out="hi") r = Orchestrator([a, b]).run(Task("text", "x")) From 426e2bb0c4972b4454adb14605e2e91d59a97713 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 18:11:35 +0000 Subject: [PATCH 10/10] Add ConsentGate: one-time, expiring, task-bound approval tokens for side-effect tasks Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EGAKcnLLeaMa9S2vGmLSFV --- ai_office_orchestrator/README.md | 1 + ai_office_orchestrator/app/core/consent.py | 40 +++++++++++++++++++ .../app/core/orchestrator.py | 11 +++-- ai_office_orchestrator/tests/test_core.py | 27 +++++++++++++ 4 files changed, 76 insertions(+), 3 deletions(-) create mode 100644 ai_office_orchestrator/app/core/consent.py diff --git a/ai_office_orchestrator/README.md b/ai_office_orchestrator/README.md index 32721af4050c..a8a76532b45f 100644 --- a/ai_office_orchestrator/README.md +++ b/ai_office_orchestrator/README.md @@ -4,6 +4,7 @@ Task -> score providers (health, quality, success, speed, cost) -> circuit break -> 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/core/consent.py b/ai_office_orchestrator/app/core/consent.py new file mode 100644 index 000000000000..e38aea98e434 --- /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/orchestrator.py b/ai_office_orchestrator/app/core/orchestrator.py index ed534490cc95..afe9bb76a031 100644 --- a/ai_office_orchestrator/app/core/orchestrator.py +++ b/ai_office_orchestrator/app/core/orchestrator.py @@ -14,7 +14,8 @@ class OrchestratorError(Exception): class Orchestrator: def __init__(self, adapters, max_attempts=3, breaker_factory=CircuitBreaker, metrics=None, - reviewer=None, strict_facts=False): + 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} @@ -38,8 +39,12 @@ def ranked(self, task): 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 and not task.approved: - raise OrchestratorError("side-effect task requires approval") + 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: diff --git a/ai_office_orchestrator/tests/test_core.py b/ai_office_orchestrator/tests/test_core.py index db522734fd72..a94a7ac41a73 100644 --- a/ai_office_orchestrator/tests/test_core.py +++ b/ai_office_orchestrator/tests/test_core.py @@ -45,6 +45,33 @@ def test_grok_registered_and_needs_key(self): 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"))