Download api_server/openai_compatible_server.py from muzissss/mum: direct link, hf CLI and curl.
- Browser
- Download file 88.7 kB
-
https://huggingface.co/spaces/muzissss/mum/resolve/main/api_server/openai_compatible_server.py
- Command line
-
hf download hf://spaces/muzissss/mum/api_server/openai_compatible_server.py
-
curl -L -o openai_compatible_server.py https://huggingface.co/spaces/muzissss/mum/resolve/main/api_server/openai_compatible_server.py
88.7 kB
# api_server/openai_compatible_server.py
# -*- coding: utf-8 -*-
import re
import json
import time
import uuid
import traceback
from threading import Lock
from typing import Dict, List, Any, Optional, Tuple
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import StreamingResponse, JSONResponse, FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from dotenv import load_dotenv
PROJECT_ROOT = Path(__file__).resolve().parents[1]
load_dotenv(dotenv_path=PROJECT_ROOT / ".env")
MODELS_JSON_PATH = PROJECT_ROOT / "models.json"
from app.config.settings import Settings
from app.core.context import RunContext
from app.core.http_client import HttpClient
from app.core.logger import JsonlLogger
from app.parsers.csrf_parser import parse_meta_csrf
from app.clients.airops_web_client import AirOpsWebClient
from app.clients.airops_api_client import AirOpsApiClient
from app.services.app_execution_service import AppExecutionService
from app.services.ai_model_catalog_service import classify_ai_models
from app.services.account_quota_service import summarize_pricing_credits_payload, summarize_tasks_packages_payload, summarize_usage_summary_payload, utc_now_iso
from app.adapters.openai_adapter import OpenAIAdapter
from app.integrations.account_store import AccountStore
from app.integrations.account_store_pg import PostgresAccountStore
from app.integrations.bootstrap_config_store import BootstrapConfigStore
from app.integrations.conversation_store import ConversationStore
from app.integrations.conversation_store_pg import PostgresConversationStore
from app.integrations.remote_config_client import RemoteConfigClient, extract_remote_settings_rows
from app.services.bootstrap_settings_service import BOOTSTRAP_SETTING_SPECS, apply_settings, snapshot_settings
from app.services.register_job_service import RegisterJobService
from api_server.admin_console_router import build_admin_router
def parse_signin_authenticity_token(html: str) -> str:
m = re.search(
r'<form[^>]*id="new_user"[^>]*>.*?name="authenticity_token"\s+value="([^"]+)"',
html,
flags=re.S | re.I,
)
if not m:
raise RuntimeError("sign_in authenticity_token not found from form#new_user")
return m.group(1)
def _to_int_or_none(v: Any) -> Optional[int]:
try:
if v is None:
return None
return int(v)
except Exception:
return None
def _to_bool(v: Any, default: bool = False) -> bool:
if v is None:
return default
if isinstance(v, bool):
return v
return str(v).strip().lower() in ("1", "true", "yes", "y", "on")
def _extract_bearer_token(auth_header: Optional[str]) -> str:
if not auth_header or not auth_header.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing Bearer token")
return auth_header.split(" ", 1)[1].strip()
def _request_client_ip(request: Request) -> str:
headers = request.headers
xff = str(headers.get("x-forwarded-for") or "").strip()
if xff:
return xff.split(",")[0].strip()
rip = str(headers.get("x-real-ip") or "").strip()
if rip:
return rip
cf = str(headers.get("cf-connecting-ip") or "").strip()
if cf:
return cf
client = request.client
return str(getattr(client, "host", "") or "")
def _build_account_store(settings: Settings):
db_url = str(getattr(settings, "database_url", "") or "").strip()
if db_url:
store = PostgresAccountStore(db_url)
return store, "postgres"
return AccountStore(settings.account_store_path), "sqlite"
def _build_conversation_store(settings: Settings):
db_url = str(getattr(settings, "database_url", "") or "").strip()
if db_url:
store = PostgresConversationStore(
db_url,
retention_days=settings.conversation_store_retention_days,
max_rows=settings.conversation_store_max_rows,
)
return store, "postgres"
store = ConversationStore(
settings.conversation_store_path,
retention_days=settings.conversation_store_retention_days,
max_rows=settings.conversation_store_max_rows,
)
return store, "sqlite"
def _build_redis_client(redis_url: str):
url = str(redis_url or "").strip()
if not url:
return None, ""
try:
import redis # type: ignore
except Exception:
return None, "redis_package_missing"
try:
client = redis.Redis.from_url(url, decode_responses=True, socket_timeout=3)
client.ping()
return client, ""
except Exception as e:
return None, str(e)
def _redis_health_snapshot(client, configured: bool, init_error: str):
if not configured:
return False, ""
if client is None:
return False, (init_error or "redis_not_ready")
try:
client.ping()
return True, ""
except Exception as e:
return False, str(e)
def _load_models_payload_from_local_file() -> Optional[Dict[str, Any]]:
if not MODELS_JSON_PATH.exists():
return None
try:
with MODELS_JSON_PATH.open("r", encoding="utf-8") as f:
payload = json.load(f)
except Exception:
return None
if not isinstance(payload, dict):
return None
models = payload.get("models")
if not isinstance(models, dict):
return None
return payload
def _format_models_payload(payload: Dict[str, Any], include_disabled: bool, workspace_id: Optional[int]) -> Dict[str, Any]:
classified = classify_ai_models(payload if isinstance(payload, dict) else {}, include_disabled=include_disabled)
flat_items = classified.get("items", [])
if not isinstance(flat_items, list):
flat_items = []
models: List[Dict[str, Any]] = []
for item in flat_items:
if not isinstance(item, dict):
continue
models.append(
{
"key": item.get("id"),
"name": item.get("name"),
"description": item.get("description"),
"category": item.get("provider"),
"enabled": _to_bool(item.get("enabled"), default=False),
"cost_tier": item.get("cost_tier"),
"priority": item.get("priority"),
"starred": _to_bool(item.get("starred"), default=False),
"family_key": item.get("family_key"),
"deprecated": _to_bool(item.get("deprecated"), default=False),
"deprecation": item.get("deprecation"),
"usecases": item.get("usecases"),
"capabilities": item.get("capabilities"),
}
)
by_category: Dict[str, List[Dict[str, Any]]] = {}
grouped = classified.get("grouped", {})
provider_map = grouped.get("by_provider", {}) if isinstance(grouped, dict) else {}
if isinstance(provider_map, dict):
for provider, rows in provider_map.items():
if not isinstance(rows, list):
continue
out_rows: List[Dict[str, Any]] = []
for row in rows:
if not isinstance(row, dict):
continue
out_rows.append(
{
"key": row.get("id"),
"name": row.get("name"),
"description": row.get("description"),
"category": row.get("provider"),
"enabled": _to_bool(row.get("enabled"), default=False),
"cost_tier": row.get("cost_tier"),
"priority": row.get("priority"),
"starred": _to_bool(row.get("starred"), default=False),
"family_key": row.get("family_key"),
"deprecated": _to_bool(row.get("deprecated"), default=False),
"deprecation": row.get("deprecation"),
"usecases": row.get("usecases"),
"capabilities": row.get("capabilities"),
}
)
by_category[str(provider)] = out_rows
enabled = [m for m in models if _to_bool(m.get("enabled"), default=False)]
# Keep legacy key name for frontend compatibility, but expose all enabled models.
chat_enabled = list(enabled)
return {
"workspace_id": workspace_id,
"summary": classified.get("summary", {}),
"grouped": grouped,
"deprecated_index": classified.get("deprecated_index", {}),
"models_by_category": by_category,
"models": models,
"enabled_models": enabled,
"chat_enabled_models": chat_enabled,
}
class SingleAccountRuntime:
def __init__(self):
self.settings = Settings()
self.log = JsonlLogger("openai_adapter_run.jsonl")
self.http = HttpClient(self.settings.base_url, timeout=self.settings.request_timeout)
self.web = AirOpsWebClient(self.http)
self.api = AirOpsApiClient(self.http)
self._base_ctx = RunContext()
self._ready = False
self._lock = Lock()
self._state_lock = Lock()
self._conversation_locks: Dict[str, Lock] = {}
self._conversation_app_ids: Dict[str, int] = {}
self._account_email: str = ""
self._account_password: str = ""
self._preferred_workspace_key: str = ""
self._available_workspaces: List[Dict[str, Any]] = []
def _to_workspace_int(self, v: Any) -> Optional[int]:
try:
if v is None:
return None
n = int(v)
if n <= 0:
return None
return n
except Exception:
return None
def _normalize_workspace_key(self, v: Any) -> str:
return str(v or "").strip().lower()
def _extract_workspace_candidates(self, payload: Dict[str, Any]) -> List[Dict[str, Any]]:
out: List[Dict[str, Any]] = []
seen_ids = set()
if not isinstance(payload, dict):
return out
# `/api/workspaces` returns `{ joined: [...], joinable: [...] }`.
# Runtime 只使用当前账号已经加入的工作区,避免误选尚未加入的 joinable 项。
for bucket in ("joined",):
rows = payload.get(bucket)
if not isinstance(rows, list):
continue
for row in rows:
if not isinstance(row, dict):
continue
wid = self._to_workspace_int(row.get("id"))
if wid is None or wid in seen_ids:
continue
seen_ids.add(wid)
out.append(
{
"id": wid,
"slug": str(row.get("slug") or "").strip(),
"name": str(row.get("name") or "").strip(),
"tier": str(row.get("tier") or "").strip(),
}
)
return out
def _fetch_workspace_candidates_locked(self) -> List[Dict[str, Any]]:
try:
csrf = str(self._base_ctx.csrf_token or "").strip()
if csrf:
r = self.api.list_workspaces(csrf, referer="/onboarding/join")
else:
r = self.api.list_workspaces_public()
self.log.info("workspaces_list_fetch", status=r.status_code)
except Exception as e:
self.log.info("workspaces_list_fetch_failed", error=str(e)[:500])
return []
if r.status_code != 200:
self.log.info("workspaces_list_unavailable", status=r.status_code)
return []
try:
payload = r.json()
except Exception:
return []
candidates = self._extract_workspace_candidates(payload if isinstance(payload, dict) else {})
self._available_workspaces = [dict(row) for row in candidates]
return [dict(row) for row in candidates]
def _resolve_workspace_from_workspace_list(self, candidates: Optional[List[Dict[str, Any]]] = None) -> Optional[Dict[str, Any]]:
if candidates is None:
candidates = [dict(row) for row in self._available_workspaces]
if not candidates:
return None
preferred = self._normalize_workspace_key(self._preferred_workspace_key)
if preferred:
for row in candidates:
if self._normalize_workspace_key(row.get("slug")) == preferred:
return row
for row in candidates:
if self._normalize_workspace_key(row.get("id")) == preferred:
return row
if len(candidates) == 1:
return candidates[0]
return None
def _apply_workspace_candidate_locked(self, row: Dict[str, Any]) -> None:
self._base_ctx.workspace_id = self._to_workspace_int(row.get("id"))
self._base_ctx.workspace_slug = str(row.get("slug") or "").strip() or None
self._base_ctx.workspace_name = str(row.get("name") or "").strip() or None
self._base_ctx.workspace_tier = str(row.get("tier") or "").strip() or None
def _clear_workspace_candidate_locked(self) -> None:
self._base_ctx.workspace_id = None
self._base_ctx.workspace_slug = None
self._base_ctx.workspace_name = None
self._base_ctx.workspace_tier = None
def _set_workspace_session_locked(self, refresh_csrf: bool = True) -> None:
if self._base_ctx.workspace_id:
self.http.session.cookies.set("workspace_id", str(self._base_ctx.workspace_id), domain="app.airops.com")
self.http.session.cookies.set("impersonating", "false", domain="app.airops.com")
if not refresh_csrf:
return
r_home = self.http.get("/")
if r_home.status_code == 200:
try:
self._base_ctx.csrf_token = parse_meta_csrf(r_home.text)
except Exception:
pass
def _upsert_workspace_candidate_locked(self, row: Dict[str, Any]) -> Dict[str, Any]:
candidate = {
"id": self._to_workspace_int(row.get("id") or row.get("workspace_id")),
"slug": str(row.get("slug") or row.get("workspace_slug") or "").strip(),
"name": str(row.get("name") or row.get("workspace_name") or "").strip(),
"tier": str(row.get("tier") or row.get("workspace_tier") or "").strip(),
"trialing": bool(row.get("trialing")) if row.get("trialing") is not None else None,
"trial_end": str(row.get("trial_end") or "").strip(),
}
wid = candidate.get("id")
if wid is None:
raise RuntimeError("workspace id missing")
replaced = False
for idx, current in enumerate(self._available_workspaces):
if self._to_workspace_int(current.get("id")) == wid:
merged = dict(current)
merged.update({k: v for k, v in candidate.items() if v not in (None, "")})
self._available_workspaces[idx] = merged
candidate = merged
replaced = True
break
if not replaced:
self._available_workspaces.append(candidate)
self._available_workspaces = sorted(self._available_workspaces, key=lambda x: int(x.get("id") or 0))
return dict(candidate)
def _workspace_usage_referer_locked(self, workspace_slug: str = "") -> str:
slug = str(workspace_slug or self._base_ctx.workspace_slug or "").strip()
if slug:
return f"/{slug}/usage/tasks?group_by=workflow"
return "/usage/tasks?group_by=workflow"
def _workspace_create_payload_locked(self, workspace_name: str) -> Dict[str, Any]:
clean_name = re.sub(r"\s+", " ", str(workspace_name or "").strip())
if not clean_name:
raise RuntimeError("workspace name required")
slug_base = re.sub(r"[^a-zA-Z0-9]+", "-", clean_name).strip("-").lower() or "workspace"
return {
"agreed_tos": True,
"allowlisted_domains": [None],
"brand_url": f"{slug_base}.com",
"name": clean_name,
"rewardful_referral_code": "",
}
def _authenticate_session_locked(self) -> None:
email = self.settings.airops_login_email
password = self.settings.airops_login_password
if not email or not password:
raise RuntimeError("AIROPS_LOGIN_EMAIL / AIROPS_LOGIN_PASSWORD not configured")
self._base_ctx.email = email
self._base_ctx.password = password
if self._base_ctx.csrf_token:
try:
r_me = self.http.get("/api/users/me", headers=self.http.browser_api_headers(referer="/", accept="application/json"))
if r_me.status_code == 200:
return
except Exception:
pass
r1 = self.web.get_signin_page()
r1.raise_for_status()
signin_tok = parse_signin_authenticity_token(r1.text)
form = [
("authenticity_token", signin_tok),
("user[email]", email),
("user[password]", password),
("user[remember_me]", "0"),
("user[remember_me]", "1"),
("commit", "Sign in"),
]
r2 = self.web.sign_in(form)
self.log.info("signin_post", status=r2.status_code, final_url=r2.url)
r_me = self.http.get("/api/users/me", headers=self.http.browser_api_headers(referer="/", accept="application/json"))
if r_me.status_code != 200:
raise RuntimeError(f"sign in failed: /api/users/me={r_me.status_code}")
me = r_me.json()
self.log.info("signin_ok", user_id=me.get("id"), email=me.get("email"))
html_source = r2.text if (r2.text and "<html" in r2.text.lower()) else None
if html_source:
self._base_ctx.csrf_token = parse_meta_csrf(html_source)
else:
r_home = self.http.get("/")
r_home.raise_for_status()
self._base_ctx.csrf_token = parse_meta_csrf(r_home.text)
def reset(self):
with self._lock:
self._ready = False
self._base_ctx = RunContext()
self._available_workspaces = []
with self._state_lock:
self._conversation_app_ids = {}
self._conversation_locks = {}
def configure_account(self, email: str, password: str, workspace_id: Optional[str] = None):
next_email = (email or "").strip()
next_password = (password or "").strip()
next_workspace_key = str(workspace_id or "").strip()
changed = (
next_email != self._account_email
or next_password != self._account_password
or next_workspace_key != self._preferred_workspace_key
)
self.settings.airops_login_email = next_email
self.settings.airops_login_password = next_password
self._account_email = next_email
self._account_password = next_password
self._preferred_workspace_key = next_workspace_key
if changed:
with self._lock:
self._ready = False
self._base_ctx = RunContext(email=next_email, password=next_password)
self._available_workspaces = []
with self._state_lock:
self._conversation_app_ids = {}
self._conversation_locks = {}
def _build_request_ctx(self) -> RunContext:
base = self._base_ctx
return RunContext(
email=base.email,
password=base.password,
authenticity_token=base.authenticity_token,
csrf_token=base.csrf_token,
workspace_id=base.workspace_id,
workspace_slug=base.workspace_slug,
workspace_name=base.workspace_name,
workspace_tier=base.workspace_tier,
oauth_client_id=base.oauth_client_id,
oauth_access_token=base.oauth_access_token,
oauth_refresh_token=base.oauth_refresh_token,
app_id=base.app_id,
request_id=base.request_id,
)
def discover_workspaces(self, force_refresh: bool = False) -> List[Dict[str, Any]]:
with self._lock:
self._authenticate_session_locked()
candidates = [dict(row) for row in self._available_workspaces]
if force_refresh or not candidates:
candidates = self._fetch_workspace_candidates_locked()
resolved = self._resolve_workspace_from_workspace_list(candidates)
if isinstance(resolved, dict):
self._apply_workspace_candidate_locked(resolved)
elif not self._ready:
self._clear_workspace_candidate_locked()
return [dict(row) for row in candidates]
def create_workspace(self, workspace_name: str) -> Dict[str, Any]:
with self._lock:
self._authenticate_session_locked()
payload = self._workspace_create_payload_locked(workspace_name)
r = self.api.create_workspace(self._base_ctx.csrf_token, payload, referer="/onboarding/setup")
r.raise_for_status()
raw = r.json()
row = raw if isinstance(raw, dict) else {}
candidate = self._upsert_workspace_candidate_locked(row)
self._apply_workspace_candidate_locked(candidate)
self._preferred_workspace_key = str(candidate.get("id") or "").strip()
self._set_workspace_session_locked(refresh_csrf=True)
self.log.info(
"workspace_created_manual",
email=self._base_ctx.email,
workspace_id=self._base_ctx.workspace_id,
workspace_slug=self._base_ctx.workspace_slug,
workspace_tier=self._base_ctx.workspace_tier,
)
return {
"workspace": {
"id": candidate.get("id"),
"slug": candidate.get("slug") or "",
"name": candidate.get("name") or "",
"tier": candidate.get("tier") or "",
},
"raw": row,
}
def activate_pro_trial(self, workspace_id: Optional[int] = None, workspace_slug: str = "") -> Dict[str, Any]:
with self._lock:
self._authenticate_session_locked()
target_id = self._to_workspace_int(workspace_id or self._base_ctx.workspace_id)
if target_id is None:
raise RuntimeError("workspace_id required for pro trial")
target_slug = str(workspace_slug or self._base_ctx.workspace_slug or "").strip()
self._preferred_workspace_key = str(target_id)
if target_id != self._base_ctx.workspace_id:
matched = False
for row in self._available_workspaces:
if self._to_workspace_int(row.get("id")) == target_id:
self._apply_workspace_candidate_locked(row)
if not target_slug:
target_slug = str(row.get("slug") or "").strip()
matched = True
break
if not matched:
self._base_ctx.workspace_id = target_id
self._base_ctx.workspace_slug = target_slug or None
self._base_ctx.workspace_name = None
self._base_ctx.workspace_tier = None
elif target_slug and not self._base_ctx.workspace_slug:
self._base_ctx.workspace_slug = target_slug
self._set_workspace_session_locked(refresh_csrf=False)
r = self.api.activate_pro_trial(
self._base_ctx.csrf_token,
target_id,
referer=self._workspace_usage_referer_locked(target_slug),
)
r.raise_for_status()
payload = r.json()
workspace = payload.get("workspace") if isinstance(payload, dict) else {}
if isinstance(workspace, dict):
merged = {
"id": workspace.get("id") or target_id,
"slug": target_slug or self._base_ctx.workspace_slug or "",
"name": self._base_ctx.workspace_name or "",
"tier": workspace.get("tier") or self._base_ctx.workspace_tier or "",
"trialing": workspace.get("trialing"),
"trial_end": workspace.get("trial_end") or "",
}
candidate = self._upsert_workspace_candidate_locked(merged)
self._apply_workspace_candidate_locked(candidate)
self.log.info(
"workspace_pro_trial_activated",
email=self._base_ctx.email,
workspace_id=target_id,
workspace_slug=target_slug,
)
return payload if isinstance(payload, dict) else {"success": False}
def _conversation_lock(self, conversation_id: str) -> Lock:
with self._state_lock:
lk = self._conversation_locks.get(conversation_id)
if lk is None:
lk = Lock()
self._conversation_locks[conversation_id] = lk
return lk
def _prepare_conversation_app(
self,
app_exec: AppExecutionService,
conversation_id: str,
messages,
model: Optional[str],
model_config: Optional[Dict[str, Any]] = None,
) -> int:
if not self.settings.reuse_app:
app_id = app_exec.create_and_patch(messages, model=model, model_config=model_config)
self.log.info("app_created_no_reuse", conversation_id=conversation_id, app_id=app_id)
return app_id
with self._state_lock:
app_id = self._conversation_app_ids.get(conversation_id)
if app_id is None:
app_id = app_exec.create_and_patch(messages, model=model, model_config=model_config)
with self._state_lock:
self._conversation_app_ids[conversation_id] = app_id
self.log.info("app_created_for_conversation", conversation_id=conversation_id, app_id=app_id)
return app_id
try:
app_exec.create_and_patch(messages, model=model, model_config=model_config, app_id=app_id)
self.log.info("app_reused_for_conversation", conversation_id=conversation_id, app_id=app_id)
return app_id
except Exception as e:
self.log.info("app_reuse_fallback_recreate", conversation_id=conversation_id, app_id=app_id, error=str(e))
new_app_id = app_exec.create_and_patch(messages, model=model, model_config=model_config)
with self._state_lock:
self._conversation_app_ids[conversation_id] = new_app_id
self.log.info("app_recreated_for_conversation", conversation_id=conversation_id, app_id=new_app_id)
return new_app_id
def _auto_detect_pusher_key(self) -> str:
return self._detect_pusher_key(prefer_cached=True)
def _detect_pusher_key(self, prefer_cached: bool = True) -> str:
current = str(getattr(self.settings, "pusher_app_key", "") or "").strip()
if prefer_cached and current:
return current
r = self.http.get("/")
if r.status_code != 200:
return ""
html = r.text or ""
patterns = [
r'"PUSHER_KEY":"([^"]+)"',
r'"pusherKey":"([^"]+)"',
r'Pusher\(["\']([A-Za-z0-9]+)["\']',
r'/app/([A-Za-z0-9]+)\?protocol=7',
]
for p in patterns:
m = re.search(p, html, flags=re.I)
if m:
return m.group(1)
return ""
def prepare_stream_transport(self):
st = str(getattr(self.settings, "stream_transport", "poll") or "").strip().lower()
if st != "pusher":
return
current = str(getattr(self.settings, "pusher_app_key", "") or "").strip()
detected = self._detect_pusher_key(prefer_cached=False)
if detected:
if detected != current:
self.settings.pusher_app_key = detected
self.log.info("pusher_key_refreshed", key=detected)
return
if not current:
self.log.info("pusher_key_not_found_fallback_poll")
def ensure_ready(self):
with self._lock:
if self._ready:
return
email = self.settings.airops_login_email
password = self.settings.airops_login_password
if not email or not password:
raise RuntimeError("AIROPS_LOGIN_EMAIL / AIROPS_LOGIN_PASSWORD not configured")
self._authenticate_session_locked()
candidates = self._fetch_workspace_candidates_locked()
resolved = self._resolve_workspace_from_workspace_list(candidates)
if isinstance(resolved, dict):
self._apply_workspace_candidate_locked(resolved)
self.log.info(
"workspace_selected_from_list",
email=email,
workspace_id=self._base_ctx.workspace_id,
workspace_slug=self._base_ctx.workspace_slug,
workspace_tier=self._base_ctx.workspace_tier,
)
elif candidates:
self._clear_workspace_candidate_locked()
self.log.info(
"workspace_selection_required",
email=email,
preferred_workspace_key=self._preferred_workspace_key,
candidate_count=len(candidates),
)
raise RuntimeError("workspace selection required: choose a workspace from /admin/workspaces")
else:
self._clear_workspace_candidate_locked()
raise RuntimeError("no joined workspaces returned by /api/workspaces")
if not self._base_ctx.workspace_id:
raise RuntimeError("workspace_id unresolved after workspace selection")
self.http.session.cookies.set("workspace_id", str(self._base_ctx.workspace_id), domain="app.airops.com")
self.http.session.cookies.set("impersonating", "false", domain="app.airops.com")
# refresh csrf
r_home2 = self.http.get("/")
if r_home2.status_code == 200:
try:
self._base_ctx.csrf_token = parse_meta_csrf(r_home2.text)
except Exception:
pass
# pusher key
detected = self._auto_detect_pusher_key()
if detected:
self.settings.pusher_app_key = detected
self.log.info("pusher_key_detected", key=detected)
else:
self.log.info("pusher_key_not_found_fallback_poll")
self._ready = True
self.log.info(
"runtime_ready_login_mode",
email=email,
workspace_id=self._base_ctx.workspace_id,
stream_transport=self.settings.stream_transport,
)
def fetch_tasks_packages(self, limit: int = 13) -> Dict[str, Any]:
if not self._ready:
self.ensure_ready()
ctx = self._build_request_ctx()
if not ctx.workspace_id:
raise RuntimeError("workspace_id missing, runtime not ready")
if not ctx.csrf_token:
raise RuntimeError("csrf_token missing, runtime not ready")
try:
r_usage = self.api.get_usage_summary(ctx.csrf_token, int(ctx.workspace_id), month_index=0)
self.log.info(
"usage_summary_fetch",
status=r_usage.status_code,
workspace_id=ctx.workspace_id,
)
r_usage.raise_for_status()
return summarize_usage_summary_payload(r_usage.json(), workspace_id=int(ctx.workspace_id))
except Exception as e:
self.log.info(
"usage_summary_failed_fallback_pricing_credits",
workspace_id=ctx.workspace_id,
error=str(e)[:500],
)
try:
r_credits = self.api.get_pricing_credits(ctx.csrf_token, int(ctx.workspace_id))
self.log.info(
"pricing_credits_fetch",
status=r_credits.status_code,
workspace_id=ctx.workspace_id,
)
r_credits.raise_for_status()
return summarize_pricing_credits_payload(r_credits.json(), workspace_id=int(ctx.workspace_id))
except Exception as e:
self.log.info(
"pricing_credits_failed_fallback_tasks_packages",
workspace_id=ctx.workspace_id,
error=str(e)[:500],
)
r_tasks = self.api.list_tasks_packages(ctx.csrf_token, int(ctx.workspace_id), limit=limit)
self.log.info(
"tasks_packages_fetch",
status=r_tasks.status_code,
workspace_id=ctx.workspace_id,
limit=limit,
)
r_tasks.raise_for_status()
return summarize_tasks_packages_payload(r_tasks.json(), workspace_id=int(ctx.workspace_id))
def fetch_ai_models(self, include_disabled: bool = False) -> Dict[str, Any]:
if not self._ready:
self.ensure_ready()
ctx = self._build_request_ctx()
if not ctx.workspace_id:
raise RuntimeError("workspace_id missing, runtime not ready")
if not ctx.csrf_token:
raise RuntimeError("csrf_token missing, runtime not ready")
r = self.api.list_ai_models(ctx.csrf_token, int(ctx.workspace_id))
self.log.info(
"ai_models_fetch",
status=r.status_code,
workspace_id=ctx.workspace_id,
)
r.raise_for_status()
payload = r.json()
return _format_models_payload(
payload if isinstance(payload, dict) else {},
include_disabled=include_disabled,
workspace_id=ctx.workspace_id,
)
def run_chat_once(
self,
messages: List[Dict[str, Any]],
conversation_id: str = "default",
model: Optional[str] = None,
model_config: Optional[Dict[str, Any]] = None,
request_id: str = "",
) -> Dict[str, Any]:
with self._conversation_lock(conversation_id):
ctx = self._build_request_ctx()
ctx.request_id = str(request_id or "")
app_exec = AppExecutionService(self.api, ctx, self.settings)
app_id = self._prepare_conversation_app(app_exec, conversation_id, messages, model, model_config=model_config)
ex = app_exec.run_test_once(app_id, messages, model=model, model_config=model_config)
execution_id = ex["id"]
final = None
chunks = []
for evt in app_exec.poll_execution(execution_id):
d = app_exec._coerce_text(evt.get("delta"))
if d:
chunks.append(d)
final = evt["raw"]
text = "".join(chunks).strip() or app_exec._coerce_text((final or {}).get("output")).strip()
return {"text": text, "final": final or {}, "execution_id": execution_id, "app_id": app_id}
def stream_chat(
self,
messages: List[Dict[str, Any]],
conversation_id: str = "default",
model: Optional[str] = None,
model_config: Optional[Dict[str, Any]] = None,
request_id: str = "",
):
with self._conversation_lock(conversation_id):
ctx = self._build_request_ctx()
ctx.request_id = str(request_id or "")
app_exec = AppExecutionService(self.api, ctx, self.settings)
app_id = self._prepare_conversation_app(app_exec, conversation_id, messages, model, model_config=model_config)
for evt in app_exec.stream_execution_pre_subscribe(app_id, messages, model=model, model_config=model_config):
yield {
"delta": app_exec._coerce_text(evt.get("delta")),
"raw": evt.get("raw") or {},
"execution_id": evt.get("execution_id"),
"app_id": app_id,
}
class AirOpsRuntime:
def __init__(self):
self.settings = Settings()
self.log = JsonlLogger("openai_adapter_run.jsonl")
self.account_store, self.account_store_backend = _build_account_store(self.settings)
self._lock = Lock()
self._workers: Dict[str, SingleAccountRuntime] = {}
self._conversation_owner: Dict[str, str] = {}
self._round_robin_idx = 0
self._manual_active_account_email = ""
self._manual_workspace_selection: Dict[str, Any] = {}
# health compatibility
self._ready = False
self._base_ctx = RunContext()
self._active_account_email = ""
self._last_error = ""
def _normalize_workspace_selection(
self,
workspace_id: Any = None,
workspace_slug: Any = None,
workspace_name: Any = None,
workspace_tier: Any = None,
account_email: Any = None,
) -> Dict[str, Any]:
out: Dict[str, Any] = {}
ws_id = str(workspace_id or "").strip()
if ws_id:
n = _to_int_or_none(ws_id)
out["workspace_id"] = str(n) if n is not None and n > 0 else ws_id
ws_slug = str(workspace_slug or "").strip()
if ws_slug:
out["workspace_slug"] = ws_slug
ws_name = str(workspace_name or "").strip()
if ws_name:
out["workspace_name"] = ws_name
ws_tier = str(workspace_tier or "").strip()
if ws_tier:
out["workspace_tier"] = ws_tier
email = str(account_email or "").strip()
if email:
out["account_email"] = email
return out
def _has_workspace_selection(self, selection: Dict[str, Any]) -> bool:
if not isinstance(selection, dict):
return False
for key in ("workspace_id", "workspace_slug", "workspace_name", "workspace_tier"):
if str(selection.get(key) or "").strip():
return True
return False
def _apply_workspace_selection_to_base_ctx_locked(self, selection: Dict[str, Any]) -> None:
ws_id = _to_int_or_none(selection.get("workspace_id"))
self._base_ctx.workspace_id = ws_id if ws_id is not None and ws_id > 0 else None
self._base_ctx.workspace_slug = str(selection.get("workspace_slug") or "").strip() or None
self._base_ctx.workspace_name = str(selection.get("workspace_name") or "").strip() or None
self._base_ctx.workspace_tier = str(selection.get("workspace_tier") or "").strip() or None
def _clear_workspace_selection_from_base_ctx_locked(self) -> None:
self._base_ctx.workspace_id = None
self._base_ctx.workspace_slug = None
self._base_ctx.workspace_name = None
self._base_ctx.workspace_tier = None
def workspace_selection_snapshot(self) -> Dict[str, Any]:
with self._lock:
if self._has_workspace_selection(self._manual_workspace_selection):
return dict(self._manual_workspace_selection)
selection = self._normalize_workspace_selection(
workspace_id=self._base_ctx.workspace_id,
workspace_slug=self._base_ctx.workspace_slug,
workspace_name=self._base_ctx.workspace_name,
workspace_tier=self._base_ctx.workspace_tier,
account_email=self._manual_active_account_email or self._active_account_email,
)
return selection if self._has_workspace_selection(selection) else {}
def restore_workspace_selection(self, payload: Dict[str, Any]) -> Dict[str, Any]:
selection = self._normalize_workspace_selection(
workspace_id=(payload or {}).get("workspace_id"),
workspace_slug=(payload or {}).get("workspace_slug"),
workspace_name=(payload or {}).get("workspace_name"),
workspace_tier=(payload or {}).get("workspace_tier"),
account_email=(payload or {}).get("account_email"),
)
with self._lock:
self._manual_workspace_selection = dict(selection)
account_email = str(selection.get("account_email") or "").strip()
if account_email:
self._manual_active_account_email = account_email
if selection:
self._apply_workspace_selection_to_base_ctx_locked(selection)
else:
self._clear_workspace_selection_from_base_ctx_locked()
return self._health_snapshot_locked()
def _load_account_candidates(self) -> List[Dict[str, Any]]:
out: List[Dict[str, Any]] = []
seen = set()
# 优先使用账号池中已验证可用的账号,降低新会话触发额外登录/建工作区的概率
try:
for row in self.account_store.list_ready_accounts(limit=50):
email = str(row.get("email") or "").strip()
password = str(row.get("password") or "").strip()
if not email or not password:
continue
key = email.lower()
if key in seen:
continue
seen.add(key)
out.append(
{
"email": email,
"password": password,
"workspace_id": row.get("workspace_id"),
"source": "account_store",
}
)
except Exception as e:
self.log.info("account_store_read_failed", error=str(e))
env_email = (self.settings.airops_login_email or "").strip()
env_password = (self.settings.airops_login_password or "").strip()
if env_email and env_password:
key = env_email.lower()
if key not in seen:
out.append({"email": env_email, "password": env_password, "workspace_id": None, "source": "env"})
seen.add(key)
if not out:
raise RuntimeError("No available login account. Configure AIROPS_LOGIN_* or seed accounts.db with ready accounts.")
return out
def _ensure_workers_locked(self):
accounts = self._load_account_candidates()
active_emails = set()
manual_workspace_id = str(self._manual_workspace_selection.get("workspace_id") or "").strip()
manual_workspace_email = str(
self._manual_workspace_selection.get("account_email") or self._manual_active_account_email or ""
).strip().lower()
for acc in accounts:
email = acc["email"]
active_emails.add(email)
worker = self._workers.get(email)
if worker is None:
worker = SingleAccountRuntime()
self._workers[email] = worker
# Keep worker runtime config aligned with the global runtime settings.
worker.settings.stream_transport = self.settings.stream_transport
worker.settings.pusher_app_key = self.settings.pusher_app_key
worker.settings.pusher_cluster = self.settings.pusher_cluster
worker.settings.poll_interval_sec = self.settings.poll_interval_sec
worker.settings.poll_timeout_sec = self.settings.poll_timeout_sec
worker.settings.request_timeout = self.settings.request_timeout
worker.settings.debug_request_trace = self.settings.debug_request_trace
preferred_workspace_id = acc.get("workspace_id")
if manual_workspace_id and manual_workspace_email and email.lower() == manual_workspace_email:
preferred_workspace_id = manual_workspace_id
worker.configure_account(email, acc["password"], workspace_id=preferred_workspace_id)
# 清理不在候选集合中的 worker 和绑定关系
for email in list(self._workers.keys()):
if email not in active_emails and email != self._manual_active_account_email:
self._workers.pop(email, None)
for cid, owner in list(self._conversation_owner.items()):
if owner not in self._workers:
self._conversation_owner.pop(cid, None)
if self._manual_active_account_email and self._manual_active_account_email not in self._workers:
self._manual_active_account_email = ""
if self._workers:
self._round_robin_idx %= len(self._workers)
else:
self._round_robin_idx = 0
def _pick_worker_locked(self, conversation_id: str) -> Tuple[str, SingleAccountRuntime]:
owner = self._conversation_owner.get(conversation_id)
if owner and owner in self._workers:
return owner, self._workers[owner]
if self._manual_active_account_email and self._manual_active_account_email in self._workers:
email = self._manual_active_account_email
self._conversation_owner[conversation_id] = email
self.log.info("account_assigned_manual", conversation_id=conversation_id, email=email)
return email, self._workers[email]
emails = list(self._workers.keys())
if not emails:
raise RuntimeError("No runtime workers available")
idx = self._round_robin_idx % len(emails)
email = emails[idx]
self._round_robin_idx = (idx + 1) % len(emails)
self._conversation_owner[conversation_id] = email
self.log.info("account_assigned_round_robin", conversation_id=conversation_id, email=email)
return email, self._workers[email]
def _get_worker_for_conversation(self, conversation_id: str) -> Tuple[str, SingleAccountRuntime]:
with self._lock:
self._ensure_workers_locked()
return self._pick_worker_locked(conversation_id)
def _mark_worker_ready(self, email: str, worker: SingleAccountRuntime):
with self._lock:
self._ready = True
self._base_ctx = worker._base_ctx
self._active_account_email = email
self._last_error = ""
# Reflect effective worker settings in runtime health/console snapshots.
self.settings.stream_transport = worker.settings.stream_transport
self.settings.pusher_cluster = worker.settings.pusher_cluster
self.settings.pusher_app_key = worker.settings.pusher_app_key
def _health_snapshot_locked(self) -> Dict[str, Any]:
selection = dict(self._manual_workspace_selection)
workspace_id = self._base_ctx.workspace_id
workspace_slug = self._base_ctx.workspace_slug
workspace_name = self._base_ctx.workspace_name
workspace_tier = self._base_ctx.workspace_tier
if selection:
selected_id = _to_int_or_none(selection.get("workspace_id"))
workspace_id = selected_id if selected_id is not None and selected_id > 0 else workspace_id
workspace_slug = str(selection.get("workspace_slug") or workspace_slug or "").strip() or None
workspace_name = str(selection.get("workspace_name") or workspace_name or "").strip() or None
workspace_tier = str(selection.get("workspace_tier") or workspace_tier or "").strip() or None
return {
"ready": self._ready,
"workspace_id": workspace_id,
"workspace_slug": workspace_slug,
"workspace_name": workspace_name,
"workspace_tier": workspace_tier,
"active_account_email": self._active_account_email,
"manual_active_account_email": self._manual_active_account_email,
"pool_size": len(self._workers),
"conversation_bindings": len(self._conversation_owner),
"last_error": self._last_error,
}
def _drop_worker(self, email: str, conversation_id: str, error_text: str):
with self._lock:
self._workers.pop(email, None)
self._conversation_owner.pop(conversation_id, None)
self.log.info("account_runtime_removed", email=email, conversation_id=conversation_id, error=error_text[:500])
def list_workspaces(self, force_refresh: bool = False) -> Dict[str, Any]:
with self._lock:
self._ensure_workers_locked()
target_email = str(
self._manual_workspace_selection.get("account_email")
or self._manual_active_account_email
or self._active_account_email
or ""
).strip()
matched_email = ""
if target_email:
for key in self._workers.keys():
if key.lower() == target_email.lower():
matched_email = key
break
if not matched_email:
matched_email = next(iter(self._workers.keys()), "")
worker = self._workers.get(matched_email)
if worker is None:
raise RuntimeError("No runtime workers available")
rows = worker.discover_workspaces(force_refresh=force_refresh)
with self._lock:
self._active_account_email = matched_email
selected = dict(self._manual_workspace_selection)
if not self._has_workspace_selection(selected):
selected = self._normalize_workspace_selection(
workspace_id=self._base_ctx.workspace_id,
workspace_slug=self._base_ctx.workspace_slug,
workspace_name=self._base_ctx.workspace_name,
workspace_tier=self._base_ctx.workspace_tier,
account_email=self._manual_active_account_email or self._active_account_email,
)
if not self._has_workspace_selection(selected) and worker._base_ctx.workspace_id:
selected = self._normalize_workspace_selection(
workspace_id=worker._base_ctx.workspace_id,
workspace_slug=worker._base_ctx.workspace_slug,
workspace_name=worker._base_ctx.workspace_name,
workspace_tier=worker._base_ctx.workspace_tier,
account_email=matched_email,
)
self._apply_workspace_selection_to_base_ctx_locked(selected)
self._last_error = ""
return {
"account_email": matched_email,
"workspaces": [dict(row) for row in rows],
"selection": dict(selected if self._has_workspace_selection(selected) else {}),
}
def _match_worker_email_locked(self, preferred_email: str = "") -> str:
target_email = str(
preferred_email
or self._manual_workspace_selection.get("account_email")
or self._manual_active_account_email
or self._active_account_email
or ""
).strip()
matched = ""
if target_email:
for key in self._workers.keys():
if key.lower() == target_email.lower():
matched = key
break
if not matched:
matched = next(iter(self._workers.keys()), "")
if not matched:
raise RuntimeError("No runtime workers available")
return matched
def _sync_account_workspace_locked(self, email: str, worker: SingleAccountRuntime, workspace_id: Any = None) -> None:
if not hasattr(self.account_store, "get_by_email") or not hasattr(self.account_store, "upsert"):
return
row = self.account_store.get_by_email(email)
if not isinstance(row, dict):
return
password = str(row.get("password") or worker._account_password or "").strip()
if not password:
return
status = str(row.get("status") or "ready").strip() or "ready"
workspace_value = str(workspace_id or row.get("workspace_id") or "").strip() or None
self.account_store.upsert(
email=email,
password=password,
status=status,
workspace_id=workspace_value,
last_error=row.get("last_error"),
failure_code=row.get("failure_code"),
retryable=row.get("retryable"),
)
def _sync_account_workspace_tier_locked(self, email: str, workspace_tier: Any = None) -> None:
if not hasattr(self.account_store, "set_quota"):
return
tier = str(workspace_tier or "").strip()
if not tier:
return
self.account_store.set_quota(
email=email,
quota_tier=tier,
quota_checked_at=utc_now_iso(),
quota_error="",
)
def create_workspace(self, workspace_name: str, email: str = "", clear_bindings: bool = True) -> Dict[str, Any]:
with self._lock:
self._ensure_workers_locked()
matched = self._match_worker_email_locked(email)
worker = self._workers.get(matched)
if worker is None:
raise RuntimeError("No runtime workers available")
result = worker.create_workspace(workspace_name)
workspace = result.get("workspace") if isinstance(result, dict) else {}
if not isinstance(workspace, dict):
workspace = {}
selection = self._normalize_workspace_selection(
workspace_id=workspace.get("id") or worker._base_ctx.workspace_id,
workspace_slug=workspace.get("slug") or worker._base_ctx.workspace_slug,
workspace_name=workspace.get("name") or worker._base_ctx.workspace_name,
workspace_tier=workspace.get("tier") or worker._base_ctx.workspace_tier,
account_email=matched,
)
with self._lock:
self._manual_workspace_selection = dict(selection)
self._manual_active_account_email = matched
self._active_account_email = matched
self._apply_workspace_selection_to_base_ctx_locked(selection)
self._ready = False
if clear_bindings:
self._conversation_owner = {}
self._sync_account_workspace_locked(matched, worker, selection.get("workspace_id"))
self._sync_account_workspace_tier_locked(matched, selection.get("workspace_tier"))
snap = self._health_snapshot_locked()
return {
"workspace": {
"id": selection.get("workspace_id") or workspace.get("id") or worker._base_ctx.workspace_id,
"slug": selection.get("workspace_slug") or workspace.get("slug") or worker._base_ctx.workspace_slug or "",
"name": selection.get("workspace_name") or workspace.get("name") or worker._base_ctx.workspace_name or "",
"tier": selection.get("workspace_tier") or workspace.get("tier") or worker._base_ctx.workspace_tier or "",
},
"account_email": matched,
"health": snap,
"raw": result.get("raw") if isinstance(result, dict) else {},
}
def activate_workspace_trial(
self,
workspace_id: Any = None,
workspace_slug: str = "",
email: str = "",
clear_bindings: bool = True,
) -> Dict[str, Any]:
with self._lock:
self._ensure_workers_locked()
matched = self._match_worker_email_locked(email)
worker = self._workers.get(matched)
if worker is None:
raise RuntimeError("No runtime workers available")
target_id = _to_int_or_none(workspace_id)
result = worker.activate_pro_trial(workspace_id=target_id, workspace_slug=workspace_slug)
payload = result if isinstance(result, dict) else {}
workspace = payload.get("workspace") if isinstance(payload.get("workspace"), dict) else {}
if not isinstance(workspace, dict):
workspace = {}
final_id = workspace.get("id") or target_id or worker._base_ctx.workspace_id
final_slug = workspace.get("slug") or workspace_slug or worker._base_ctx.workspace_slug or ""
final_name = workspace.get("name") or worker._base_ctx.workspace_name or ""
final_tier = workspace.get("tier") or worker._base_ctx.workspace_tier or ""
selection = self._normalize_workspace_selection(
workspace_id=final_id,
workspace_slug=final_slug,
workspace_name=final_name,
workspace_tier=final_tier,
account_email=matched,
)
with self._lock:
self._manual_workspace_selection = dict(selection)
self._manual_active_account_email = matched
self._active_account_email = matched
self._apply_workspace_selection_to_base_ctx_locked(selection)
self._ready = False
if clear_bindings:
self._conversation_owner = {}
self._sync_account_workspace_locked(matched, worker, selection.get("workspace_id"))
self._sync_account_workspace_tier_locked(matched, selection.get("workspace_tier"))
snap = self._health_snapshot_locked()
return {
"success": bool(payload.get("success", True)),
"workspace": {
"id": selection.get("workspace_id") or final_id,
"slug": selection.get("workspace_slug") or final_slug,
"name": selection.get("workspace_name") or final_name,
"tier": selection.get("workspace_tier") or final_tier,
"trialing": workspace.get("trialing"),
"trial_end": str(workspace.get("trial_end") or "").strip(),
},
"account_email": matched,
"health": snap,
"raw": payload,
}
def set_active_account(self, email: str, clear_bindings: bool = True) -> Dict[str, Any]:
target = str(email or "").strip().lower()
if not target:
raise RuntimeError("email required")
with self._lock:
self._ensure_workers_locked()
matched = ""
for key in self._workers.keys():
if key.lower() == target:
matched = key
break
if not matched:
row = self.account_store.get_by_email(email) if hasattr(self.account_store, "get_by_email") else None
if not isinstance(row, dict):
raise RuntimeError("account not found")
password = str(row.get("password") or "").strip()
if not password:
raise RuntimeError("account password missing")
matched = str(row.get("email") or email).strip()
worker = self._workers.get(matched)
if worker is None:
worker = SingleAccountRuntime()
self._workers[matched] = worker
worker.configure_account(matched, password, workspace_id=row.get("workspace_id"))
self._manual_active_account_email = matched
if self._manual_workspace_selection:
self._manual_workspace_selection["account_email"] = matched
if clear_bindings:
self._conversation_owner = {}
self._active_account_email = matched
return self._health_snapshot_locked()
def set_active_workspace(
self,
workspace_id: str,
workspace_slug: str = "",
workspace_name: str = "",
workspace_tier: str = "",
email: str = "",
clear_bindings: bool = True,
) -> Dict[str, Any]:
selection = self._normalize_workspace_selection(
workspace_id=workspace_id,
workspace_slug=workspace_slug,
workspace_name=workspace_name,
workspace_tier=workspace_tier,
account_email=email,
)
ws_id = str(selection.get("workspace_id") or "").strip()
if not ws_id:
raise RuntimeError("workspace_id required")
with self._lock:
self._ensure_workers_locked()
matched = ""
target_email = str(selection.get("account_email") or self._manual_active_account_email or self._active_account_email or "").strip()
if target_email:
for key in self._workers.keys():
if key.lower() == target_email.lower():
matched = key
break
if not matched:
matched = next(iter(self._workers.keys()), "")
if not matched:
raise RuntimeError("No runtime workers available")
selection["account_email"] = matched
self._manual_workspace_selection = dict(selection)
self._manual_active_account_email = matched
self._active_account_email = matched
self._apply_workspace_selection_to_base_ctx_locked(selection)
self._ready = False
if clear_bindings:
self._conversation_owner = {}
worker = self._workers.get(matched)
if worker is not None:
worker.configure_account(matched, worker._account_password, workspace_id=ws_id)
return self._health_snapshot_locked()
def clear_active_account(self, clear_bindings: bool = False) -> Dict[str, Any]:
with self._lock:
self._manual_active_account_email = ""
if clear_bindings:
self._conversation_owner = {}
return self._health_snapshot_locked()
def clear_active_workspace(self, clear_bindings: bool = False) -> Dict[str, Any]:
with self._lock:
self._manual_workspace_selection = {}
self._manual_active_account_email = ""
self._ready = False
self._clear_workspace_selection_from_base_ctx_locked()
if clear_bindings:
self._conversation_owner = {}
return self._health_snapshot_locked()
def _worker_attempt_limit(self) -> int:
with self._lock:
self._ensure_workers_locked()
return max(len(self._workers), 1)
def ensure_ready(self, conversation_id: str = "default") -> SingleAccountRuntime:
with self._lock:
self._ensure_workers_locked()
max_attempts = max(len(self._workers), 1)
attempts = 0
last_err: Optional[Exception] = None
while attempts < max_attempts:
email, worker = self._get_worker_for_conversation(conversation_id)
try:
worker.ensure_ready()
self._mark_worker_ready(email, worker)
return worker
except Exception as e:
last_err = e
self._drop_worker(email, conversation_id, str(e))
attempts += 1
with self._lock:
self._last_error = str(e)
raise RuntimeError(f"all account runtimes failed: {last_err}")
def run_chat_once(
self,
messages: List[Dict[str, Any]],
conversation_id: str = "default",
model: Optional[str] = None,
model_config: Optional[Dict[str, Any]] = None,
request_id: str = "",
) -> Dict[str, Any]:
attempts = 0
max_attempts = self._worker_attempt_limit()
last_err: Optional[Exception] = None
while attempts < max_attempts:
email, worker = self._get_worker_for_conversation(conversation_id)
try:
worker.ensure_ready()
self._mark_worker_ready(email, worker)
res = worker.run_chat_once(
messages,
conversation_id=conversation_id,
model=model,
model_config=model_config,
request_id=request_id,
)
if "account_email" not in res:
res["account_email"] = email
return res
except Exception as e:
last_err = e
self.log.info("account_chat_failed", conversation_id=conversation_id, email=email, error=str(e)[:500])
self._drop_worker(email, conversation_id, str(e))
attempts += 1
with self._lock:
self._last_error = str(e)
raise RuntimeError(f"all account chat attempts failed: {last_err}")
def stream_chat(
self,
messages: List[Dict[str, Any]],
conversation_id: str = "default",
model: Optional[str] = None,
model_config: Optional[Dict[str, Any]] = None,
request_id: str = "",
):
attempts = 0
max_attempts = self._worker_attempt_limit()
last_err: Optional[Exception] = None
while attempts < max_attempts:
email, worker = self._get_worker_for_conversation(conversation_id)
emitted = False
try:
worker.ensure_ready()
worker.prepare_stream_transport()
self._mark_worker_ready(email, worker)
for evt in worker.stream_chat(
messages,
conversation_id=conversation_id,
model=model,
model_config=model_config,
request_id=request_id,
):
if evt.get("delta"):
emitted = True
evt["account_email"] = email
yield evt
return
except Exception as e:
last_err = e
self.log.info(
"account_stream_failed",
conversation_id=conversation_id,
email=email,
emitted=emitted,
error=str(e)[:500],
)
# 已经输出过 token,就不能静默重试,避免流式结果重复。
if emitted:
raise
self._drop_worker(email, conversation_id, str(e))
attempts += 1
with self._lock:
self._last_error = str(e)
raise RuntimeError(f"all account stream attempts failed: {last_err}")
def quota_snapshot(self, limit: int = 13, conversation_id: str = "__admin_quota__") -> Dict[str, Any]:
attempts = 0
max_attempts = self._worker_attempt_limit()
last_err: Optional[Exception] = None
while attempts < max_attempts:
email, worker = self._get_worker_for_conversation(conversation_id)
try:
worker.ensure_ready()
self._mark_worker_ready(email, worker)
data = worker.fetch_tasks_packages(limit=limit)
data["account_email"] = email
return data
except Exception as e:
last_err = e
self.log.info("account_quota_failed", conversation_id=conversation_id, email=email, error=str(e)[:500])
self._drop_worker(email, conversation_id, str(e))
attempts += 1
with self._lock:
self._last_error = str(e)
raise RuntimeError(f"all account quota attempts failed: {last_err}")
def refresh_account_quotas(
self,
limit: int = 13,
account_limit: int = 200,
statuses: Optional[List[str]] = None,
sleep_sec: float = 0.0,
) -> Dict[str, Any]:
rows: List[Dict[str, Any]] = []
if hasattr(self.account_store, "list_accounts_full"):
raw_rows = self.account_store.list_accounts_full(limit=max(int(account_limit), 1))
if isinstance(raw_rows, list):
rows = [r for r in raw_rows if isinstance(r, dict)]
elif hasattr(self.account_store, "list_accounts"):
base_rows = self.account_store.list_accounts(limit=max(int(account_limit), 1))
if isinstance(base_rows, list):
for row in base_rows:
if not isinstance(row, dict):
continue
email = str(row.get("email") or "").strip()
if not email:
continue
full = self.account_store.get_by_email(email) if hasattr(self.account_store, "get_by_email") else None
if isinstance(full, dict):
rows.append(full)
else:
rows.append(row)
status_filter = {str(s).strip().lower() for s in (statuses or []) if str(s).strip()}
if status_filter:
rows = [r for r in rows if str(r.get("status") or "").strip().lower() in status_filter]
report_rows: List[Dict[str, Any]] = []
updated = 0
failed = 0
skipped = 0
for row in rows:
email = str(row.get("email") or "").strip()
password = str(row.get("password") or "").strip()
workspace_id = str(row.get("workspace_id") or "").strip() or None
status = str(row.get("status") or "").strip()
if not email or not password:
skipped += 1
report_rows.append(
{
"email": email,
"status": status,
"workspace_id": workspace_id,
"ok": False,
"error": "missing email/password",
}
)
continue
worker = SingleAccountRuntime()
worker.configure_account(email, password, workspace_id=workspace_id)
try:
worker.ensure_ready()
data = worker.fetch_tasks_packages(limit=max(int(limit), 1))
summary = (data or {}).get("summary") or {}
if hasattr(self.account_store, "set_quota"):
self.account_store.set_quota(
email=email,
quota_limit=summary.get("limit"),
quota_used=summary.get("used"),
quota_remaining=summary.get("remaining"),
quota_type=summary.get("type"),
quota_active=summary.get("active"),
quota_tier=summary.get("tier"),
quota_checked_at=summary.get("checked_at"),
quota_error="",
)
updated += 1
report_rows.append(
{
"email": email,
"status": status,
"workspace_id": data.get("workspace_id"),
"ok": True,
"summary": summary,
}
)
except Exception as e:
err = str(e)[:500]
failed += 1
if hasattr(self.account_store, "set_quota"):
self.account_store.set_quota(
email=email,
quota_checked_at=utc_now_iso(),
quota_error=err,
)
report_rows.append(
{
"email": email,
"status": status,
"workspace_id": workspace_id,
"ok": False,
"error": err,
}
)
if sleep_sec > 0:
time.sleep(max(float(sleep_sec), 0.0))
return {
"total": len(rows),
"updated": updated,
"failed": failed,
"skipped": skipped,
"rows": report_rows,
}
def available_models(self, conversation_id: str = "__admin_models__", include_disabled: bool = False) -> Dict[str, Any]:
local_payload = _load_models_payload_from_local_file()
if local_payload is not None:
data = _format_models_payload(
local_payload,
include_disabled=include_disabled,
workspace_id=self._base_ctx.workspace_id,
)
data["source"] = "local_models_json"
data["account_email"] = self._active_account_email
return data
attempts = 0
max_attempts = self._worker_attempt_limit()
last_err: Optional[Exception] = None
while attempts < max_attempts:
email, worker = self._get_worker_for_conversation(conversation_id)
try:
worker.ensure_ready()
self._mark_worker_ready(email, worker)
data = worker.fetch_ai_models(include_disabled=include_disabled)
data["source"] = "remote_airops_api"
data["account_email"] = email
return data
except Exception as e:
last_err = e
self.log.info("account_models_failed", conversation_id=conversation_id, email=email, error=str(e)[:500])
self._drop_worker(email, conversation_id, str(e))
attempts += 1
with self._lock:
self._last_error = str(e)
raise RuntimeError(f"all account models attempts failed: {last_err}")
def reset(self):
preserved_selection = self.workspace_selection_snapshot()
with self._lock:
for w in self._workers.values():
try:
w.reset()
except Exception:
pass
self._workers = {}
self._conversation_owner = {}
self._round_robin_idx = 0
self._manual_active_account_email = str(preserved_selection.get("account_email") or "").strip()
self._manual_workspace_selection = dict(preserved_selection or {})
self._ready = False
self._base_ctx = RunContext()
if preserved_selection:
self._apply_workspace_selection_to_base_ctx_locked(preserved_selection)
self._active_account_email = ""
self._last_error = ""
def health_snapshot(self) -> Dict[str, Any]:
with self._lock:
return self._health_snapshot_locked()
def _load_remote_settings_if_configured(settings: Settings):
remote_url = str(getattr(settings, "remote_config_url", "") or "").strip()
deploy_key = str(getattr(settings, "deploy_key", "") or "").strip()
if not remote_url:
return False, {}, {}, ""
if not deploy_key:
return False, {}, {}, "REMOTE_CONFIG_URL is set but DEPLOY_KEY is empty"
client = RemoteConfigClient(
url=remote_url,
deploy_key=deploy_key,
timeout_sec=getattr(settings, "remote_config_timeout_sec", 10),
auth_header=getattr(settings, "remote_config_auth_header", "Authorization"),
)
payload = client.fetch()
rows = extract_remote_settings_rows(payload)
if not rows:
return False, {}, {}, "remote config payload has no settings"
updated, ignored = apply_settings(settings, rows, BOOTSTRAP_SETTING_SPECS)
return bool(updated), updated, ignored, ""
app = FastAPI(title="AirOps OpenAI-Compatible API", version="1.6.0")
runtime = AirOpsRuntime()
settings = runtime.settings
bootstrap_defaults = snapshot_settings(settings, BOOTSTRAP_SETTING_SPECS)
bootstrap_store = BootstrapConfigStore(getattr(settings, "bootstrap_config_path", "data/bootstrap_config.json"))
bootstrap_init_error = ""
bootstrap_loaded = False
try:
loaded = bootstrap_store.load()
if isinstance(loaded, dict):
loaded_rows = loaded.get("settings")
if not isinstance(loaded_rows, dict):
loaded_rows = loaded
updated, _ignored = apply_settings(settings, loaded_rows, BOOTSTRAP_SETTING_SPECS)
bootstrap_loaded = bool(updated)
loaded_workspace_selection = loaded.get("workspace_selection")
if isinstance(loaded_workspace_selection, dict):
runtime.restore_workspace_selection(loaded_workspace_selection)
except Exception as e:
bootstrap_init_error = str(e)
remote_config_loaded = False
remote_config_error = ""
remote_config_updated: Dict[str, Any] = {}
remote_config_ignored: Dict[str, str] = {}
try:
remote_config_loaded, remote_config_updated, remote_config_ignored, remote_config_error = _load_remote_settings_if_configured(settings)
except Exception as e:
remote_config_error = str(e)
remote_config_blocking_error = ""
if str(getattr(settings, "remote_config_url", "") or "").strip() and (not remote_config_loaded):
reason = str(remote_config_error or "remote config is not loaded").strip()
remote_config_blocking_error = (
"remote config bootstrap failed; service startup is blocked because REMOTE_CONFIG_URL is configured. "
f"url={getattr(settings, 'remote_config_url', '')}; "
f"reason={reason}. "
"Fix remote config endpoint/auth, then restart service; or unset REMOTE_CONFIG_URL to use local bootstrap."
)
# runtime is created before bootstrap/remote settings injection.
# Rebuild account store once startup settings are finalized.
runtime.account_store, runtime.account_store_backend = _build_account_store(settings)
conv_store, conv_store_backend = _build_conversation_store(settings)
redis_client, redis_init_error = _build_redis_client(settings.redis_url)
adapter = OpenAIAdapter(runtime, conv_store)
request_trace_log = JsonlLogger("request_trace.jsonl")
register_jobs = RegisterJobService(settings, runtime.account_store)
console_dir = PROJECT_ROOT / "app" / "web" / "console"
bootstrap_dir = PROJECT_ROOT / "app" / "web" / "bootstrap"
app.mount("/console/assets", StaticFiles(directory=str(console_dir)), name="console_assets")
def check_openai_auth(auth_header: Optional[str]):
token = _extract_bearer_token(auth_header)
if token != settings.openai_bearer_token:
raise HTTPException(status_code=401, detail="Invalid API key")
def check_admin_auth(auth_header: Optional[str]):
token = _extract_bearer_token(auth_header)
expected = settings.admin_bearer_token or settings.openai_bearer_token
if token != expected:
raise HTTPException(status_code=401, detail="Invalid admin API key")
def ensure_remote_config_ready():
if remote_config_blocking_error:
raise HTTPException(status_code=503, detail=remote_config_blocking_error)
app.include_router(
build_admin_router(
runtime=runtime,
settings=settings,
conv_store=conv_store,
account_store=runtime.account_store,
register_jobs=register_jobs,
check_auth=check_admin_auth,
bootstrap_store=bootstrap_store,
bootstrap_initialized=bootstrap_loaded,
bootstrap_defaults=bootstrap_defaults,
)
)
@app.get("/console")
def console_page():
index_path = console_dir / "index.html"
if not index_path.exists():
return HTMLResponse("<h3>Console page not found.</h3>", status_code=404)
return FileResponse(str(index_path))
@app.get("/management.html")
def management_page():
# Keep compatibility with CPA-style deployment entry.
return console_page()
@app.get("/bootstrap")
def bootstrap_page():
index_path = bootstrap_dir / "index.html"
if not index_path.exists():
return HTMLResponse("<h3>Bootstrap page not found.</h3>", status_code=404)
return FileResponse(str(index_path))
@app.get("/bootstrap.html")
def bootstrap_page_compat():
return bootstrap_page()
@app.get("/health")
def health():
snap = runtime.health_snapshot()
redis_ready, redis_error = _redis_health_snapshot(
redis_client,
configured=bool(getattr(settings, "redis_url", "")),
init_error=redis_init_error,
)
return {
"ok": True,
"ready": snap["ready"],
"workspace_id": snap["workspace_id"],
"workspace_slug": snap.get("workspace_slug"),
"workspace_name": snap.get("workspace_name"),
"workspace_tier": snap.get("workspace_tier"),
"active_account_email": snap["active_account_email"],
"manual_active_account_email": snap.get("manual_active_account_email") or "",
"account_pool_size": snap["pool_size"],
"conversation_bindings": snap["conversation_bindings"],
"last_error": snap.get("last_error") or "",
"conversation_store_items": conv_store.count(),
"account_store_backend": getattr(runtime, "account_store_backend", "unknown"),
"conversation_store_backend": conv_store_backend,
"stream_transport": settings.stream_transport,
"pusher_key_loaded": bool(getattr(runtime.settings, "pusher_app_key", "")),
"admin_token_separated": bool(getattr(settings, "admin_bearer_token", "")),
"redis_configured": bool(getattr(settings, "redis_url", "")),
"database_configured": bool(getattr(settings, "database_url", "")),
"redis_ready": redis_ready,
"redis_init_error": redis_error,
"bootstrap_initialized": bool(bootstrap_store.exists()),
"bootstrap_token_configured": bool(getattr(settings, "bootstrap_token", "")),
"bootstrap_init_error": bootstrap_init_error,
"remote_config_enabled": bool(getattr(settings, "remote_config_url", "")),
"remote_config_loaded": bool(remote_config_loaded),
"remote_config_updated_count": len(remote_config_updated),
"remote_config_ignored_count": len(remote_config_ignored),
"remote_config_error": remote_config_error,
"remote_config_blocking": bool(remote_config_blocking_error),
"remote_config_blocking_error": remote_config_blocking_error,
}
@app.get("/v1/models")
def models(authorization: Optional[str] = Header(None)):
check_openai_auth(authorization)
ensure_remote_config_ready()
try:
catalog = runtime.available_models(conversation_id="__openai_models__", include_disabled=False)
except Exception:
catalog = {}
rows = catalog.get("enabled_models")
if not isinstance(rows, list):
rows = catalog.get("models")
if not isinstance(rows, list):
rows = []
data: List[Dict[str, Any]] = []
seen = set()
for item in rows:
if not isinstance(item, dict):
continue
model_id = str(item.get("key") or "").strip()
if not model_id or model_id in seen:
continue
seen.add(model_id)
data.append(
{
"id": model_id,
"object": "model",
"owned_by": str(item.get("category") or item.get("provider") or "airops"),
}
)
if not data:
data = [{"id": settings.default_model, "object": "model", "owned_by": "airops"}]
return {"object": "list", "data": data}
@app.get("/v1/credits")
def credits(authorization: Optional[str] = Header(None), limit: int = 13):
check_openai_auth(authorization)
ensure_remote_config_ready()
try:
snap = runtime.quota_snapshot(limit=max(int(limit), 1), conversation_id="__openai_credits__")
except Exception as e:
raise HTTPException(status_code=500, detail=f"quota fetch failed: {e}")
summary = snap.get("summary") if isinstance(snap, dict) else {}
if not isinstance(summary, dict):
summary = {}
limit_value = _to_int_or_none(summary.get("limit"))
used_value = _to_int_or_none(summary.get("used"))
remaining_value = _to_int_or_none(summary.get("remaining"))
if remaining_value is None and limit_value is not None and used_value is not None:
remaining_value = max(limit_value - used_value, 0)
return {
"object": "credits",
"account_email": (snap or {}).get("account_email"),
"workspace_id": (snap or {}).get("workspace_id"),
"remaining": remaining_value,
"used": used_value,
"limit": limit_value,
"active": summary.get("active"),
"type": summary.get("type"),
"tier": summary.get("tier"),
"checked_at": summary.get("checked_at"),
"packages_count": (snap or {}).get("packages_count"),
"active_package": (snap or {}).get("active_package") or {},
"data": {
"total_usage": f"{used_value if used_value is not None else 0} - {limit_value if limit_value is not None else 0}",
"remaining": remaining_value if remaining_value is not None else 0,
"used": used_value,
"limit": limit_value,
},
}
@app.post("/v1/chat/completions")
def chat_completions(payload: Dict[str, Any], request: Request, authorization: Optional[str] = Header(None)):
check_openai_auth(authorization)
ensure_remote_config_ready()
trace_enabled = bool(getattr(settings, "debug_request_trace", False))
req_headers = request.headers
request_id = str(req_headers.get("x-request-id") or "").strip()
if not request_id:
request_id = f"req-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}"
client_ip = _request_client_ip(request)
incoming_messages = payload.get("messages")
if isinstance(incoming_messages, list):
incoming_count = len(incoming_messages)
else:
incoming_count = 0
stream_raw = payload.get("stream")
stream_bool = bool(stream_raw) if stream_raw is not None else False
if trace_enabled:
request_trace_log.info(
"request_trace_in",
request_id=request_id,
method=request.method,
path=request.url.path,
client_ip=client_ip,
user_agent=str(req_headers.get("user-agent") or ""),
origin=str(req_headers.get("origin") or ""),
referer=str(req_headers.get("referer") or ""),
content_type=str(req_headers.get("content-type") or ""),
stream=stream_bool,
stream_raw=stream_raw,
model=str(payload.get("model") or ""),
request_messages=incoming_count,
payload_keys=sorted([str(k) for k in payload.keys()]),
)
request_trace_log.info(
"request_trace_in_payload",
request_id=request_id,
payload=payload,
)
try:
if bool(payload.get("force_rebootstrap", False)):
runtime.reset()
try:
res = adapter.handle_chat_completions(payload, request_id=request_id)
except ValueError as e:
if trace_enabled:
request_trace_log.info(
"request_trace_out",
request_id=request_id,
stage="validate",
success=False,
http_status=400,
error=str(e),
)
raise HTTPException(status_code=400, detail=str(e))
if not res.get("stream"):
if trace_enabled:
request_trace_log.info(
"request_trace_out",
request_id=request_id,
stage="response",
success=True,
stream=False,
http_status=200,
)
request_trace_log.info(
"request_trace_out_payload",
request_id=request_id,
stream=False,
payload=res.get("response"),
)
return res["response"]
if trace_enabled:
request_trace_log.info(
"request_trace_out",
request_id=request_id,
stage="response",
success=True,
stream=True,
http_status=200,
)
return StreamingResponse(res["generator"], media_type="text/event-stream")
except HTTPException:
raise
except Exception as e:
if trace_enabled:
request_trace_log.info(
"request_trace_out",
request_id=request_id,
stage="exception",
success=False,
http_status=500,
error=str(e),
)
traceback.print_exc()
return JSONResponse(status_code=500, content={"error": str(e), "type": e.__class__.__name__})
# api_server/openai_compatible_server.py
# -*- coding: utf-8 -*-
import re
import json
import time
import uuid
import traceback
from threading import Lock
from typing import Dict, List, Any, Optional, Tuple
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import StreamingResponse, JSONResponse, FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from dotenv import load_dotenv
PROJECT_ROOT = Path(__file__).resolve().parents[1]
load_dotenv(dotenv_path=PROJECT_ROOT / ".env")
MODELS_JSON_PATH = PROJECT_ROOT / "models.json"
from app.config.settings import Settings
from app.core.context import RunContext
from app.core.http_client import HttpClient
from app.core.logger import JsonlLogger
from app.parsers.csrf_parser import parse_meta_csrf
from app.clients.airops_web_client import AirOpsWebClient
from app.clients.airops_api_client import AirOpsApiClient
from app.services.app_execution_service import AppExecutionService
from app.services.ai_model_catalog_service import classify_ai_models
from app.services.account_quota_service import summarize_pricing_credits_payload, summarize_tasks_packages_payload, summarize_usage_summary_payload, utc_now_iso
from app.adapters.openai_adapter import OpenAIAdapter
from app.integrations.account_store import AccountStore
from app.integrations.account_store_pg import PostgresAccountStore
from app.integrations.bootstrap_config_store import BootstrapConfigStore
from app.integrations.conversation_store import ConversationStore
from app.integrations.conversation_store_pg import PostgresConversationStore
from app.integrations.remote_config_client import RemoteConfigClient, extract_remote_settings_rows
from app.services.bootstrap_settings_service import BOOTSTRAP_SETTING_SPECS, apply_settings, snapshot_settings
from app.services.register_job_service import RegisterJobService
from api_server.admin_console_router import build_admin_router
def parse_signin_authenticity_token(html: str) -> str:
m = re.search(
r'<form[^>]*id="new_user"[^>]*>.*?name="authenticity_token"\s+value="([^"]+)"',
html,
flags=re.S | re.I,
)
if not m:
raise RuntimeError("sign_in authenticity_token not found from form#new_user")
return m.group(1)
def _to_int_or_none(v: Any) -> Optional[int]:
try:
if v is None:
return None
return int(v)
except Exception:
return None
def _to_bool(v: Any, default: bool = False) -> bool:
if v is None:
return default
if isinstance(v, bool):
return v
return str(v).strip().lower() in ("1", "true", "yes", "y", "on")
def _extract_bearer_token(auth_header: Optional[str]) -> str:
if not auth_header or not auth_header.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing Bearer token")
return auth_header.split(" ", 1)[1].strip()
def _request_client_ip(request: Request) -> str:
headers = request.headers
xff = str(headers.get("x-forwarded-for") or "").strip()
if xff:
return xff.split(",")[0].strip()
rip = str(headers.get("x-real-ip") or "").strip()
if rip:
return rip
cf = str(headers.get("cf-connecting-ip") or "").strip()
if cf:
return cf
client = request.client
return str(getattr(client, "host", "") or "")
def _build_account_store(settings: Settings):
db_url = str(getattr(settings, "database_url", "") or "").strip()
if db_url:
store = PostgresAccountStore(db_url)
return store, "postgres"
return AccountStore(settings.account_store_path), "sqlite"