recovered snapshot from suspended aaronjaworski710 (history unavailable)

This commit is contained in:
reform
2026-10-23 20:04:00 +03:00
commit 9b3dd46ab4
31 changed files with 8900 additions and 0 deletions
View File
+114
View File
@@ -0,0 +1,114 @@
import time
import threading
from typing import Dict, List
from app.logger import logger
from app.notion_client import NotionOpusAPI
class AccountPool:
def __init__(self, accounts: List[dict]):
"""
从配置列表初始化,每个 dict 对应一组凭据。
同时初始化客户端实例和它们的状态。
"""
if not accounts:
raise ValueError("账号池初始化失败:未提供任何账号配置。")
self.clients = [NotionOpusAPI(acc) for acc in accounts]
# 记录每个客户端的冷却释放时间戳(0 表示可用)
self.cooldown_until = [0.0 for _ in self.clients]
# 轮询索引
self._current_index = 0
self._lock = threading.Lock()
def get_client(self, wait_if_cooling: bool = True) -> NotionOpusAPI:
"""
轮询(Round-Robin)返回下一个可用客户端。
过滤掉正处于冷却期中的客户端。
如果 wait_if_cooling=True(默认),当所有账号都在冷却时,
会等待最近的冷却结束后返回,而不是抛异常。
"""
now = time.time()
with self._lock:
start_index = self._current_index
while True:
idx = self._current_index
# 如果过了冷却时间,视为可用
if self.cooldown_until[idx] <= now:
# 轮询步进
self._current_index = (self._current_index + 1) % len(self.clients)
return self.clients[idx]
# 不可用则顺延
self._current_index = (self._current_index + 1) % len(self.clients)
# 如果转了一圈都没找到可用的
if self._current_index == start_index:
next_available = min(self.cooldown_until)
wait_seconds = max(0.5, next_available - now)
if wait_if_cooling and wait_seconds <= 15:
# 等待冷却结束后重新尝试
logger.info(
f"All accounts cooling, waiting {wait_seconds:.1f}s",
extra={
"request_info": {
"event": "account_pool_wait_cooling",
"wait_seconds": round(wait_seconds, 1),
}
},
)
# 释放锁再 sleep,避免阻塞其他线程
self._lock.release()
try:
time.sleep(wait_seconds)
finally:
self._lock.acquire()
# 更新时间后重新扫描
now = time.time()
continue
raise RuntimeError(
f"所有账号冷却中,请在 {max(1, int(wait_seconds))} 秒后重试。"
)
def get_status_summary(self) -> Dict[str, int]:
"""返回账号池简要状态,供健康检查和日志使用。"""
now = time.time()
with self._lock:
active = sum(1 for ts in self.cooldown_until if ts <= now)
cooling = len(self.cooldown_until) - active
return {
"total": len(self.clients),
"active": active,
"cooling": cooling,
}
def mark_failed(self, client: NotionOpusAPI, cooldown_seconds: int = 3):
"""
标记某个客户端为临时不可用(默认冷却 3 秒后恢复)。
"""
with self._lock:
try:
idx = self.clients.index(client)
# 记录未来的冷却解封时间
self.cooldown_until[idx] = time.time() + cooldown_seconds
logger.warning(
"Account marked as failed",
extra={
"request_info": {
"event": "account_failed",
"account": client.account_key,
"space_id": client.space_id,
"cooldown_seconds": cooldown_seconds,
}
},
)
except ValueError:
logger.warning(
"Attempted to mark unknown account as failed",
extra={"request_info": {"event": "account_failed_unknown"}},
)
View File
+1943
View File
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
import time
from typing import Dict, Any
from fastapi import APIRouter
from app.model_registry import get_display_name, get_model_icon, list_available_models
router = APIRouter()
@router.get("/models", tags=["models"])
async def list_models() -> Dict[str, Any]:
"""
列出可用的模型,兼容 OpenAI 格式。
"""
created_at = int(time.time())
return {
"object": "list",
"data": [
{
"id": model_id,
"object": "model",
"created": created_at,
"owned_by": "notion",
"permission": [],
"root": model_id,
"parent": None,
"display_name": get_display_name(model_id),
"icon": get_model_icon(model_id),
}
for model_id in list_available_models()
],
}
+66
View File
@@ -0,0 +1,66 @@
import os
import json
from dotenv import load_dotenv
# 加载 .env 文件中的环境变量(override=True 确保 .env 优先于系统环境变量)
load_dotenv(override=True)
REQUIRED_ACCOUNT_FIELDS = {"token_v2", "space_id", "user_id"}
def load_accounts():
"""
从 accounts.json 文件或环境变量 NOTION_ACCOUNTS 加载账号配置。
优先级:accounts.json > NOTION_ACCOUNTS 环境变量
"""
# 优先从 accounts.json 文件读取
accounts_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "accounts.json")
accounts_json = None
if os.path.exists(accounts_file):
with open(accounts_file, "r", encoding="utf-8") as f:
accounts_json = f.read().strip()
# 回退到环境变量
if not accounts_json:
accounts_json = os.getenv("NOTION_ACCOUNTS")
if not accounts_json:
raise ValueError("未找到账号配置:请创建 accounts.json 文件或设置 NOTION_ACCOUNTS 环境变量。")
try:
accounts = json.loads(accounts_json)
if not isinstance(accounts, list) or len(accounts) == 0:
raise ValueError("账号配置格式不正确,应提供非空的 JSON 数组。")
for idx, account in enumerate(accounts):
if not isinstance(account, dict):
raise ValueError(f"账号配置[{idx}] 必须是对象。")
missing = sorted(field for field in REQUIRED_ACCOUNT_FIELDS if not account.get(field))
if missing:
raise ValueError(f"账号配置[{idx}] 缺少必要字段: {', '.join(missing)}")
return accounts
except json.JSONDecodeError as e:
raise ValueError(f"解析账号配置失败: {e}")
# 全局配置对象
ACCOUNTS = load_accounts()
# FastAPI 服务配置
API_KEY = os.getenv("API_KEY", "")
SILICONFLOW_API_KEY = os.getenv("SILICONFLOW_API_KEY", "")
HOST = os.getenv("HOST", "0.0.0.0")
PORT = int(os.getenv("PORT", "8000"))
ALLOWED_ORIGINS = [origin.strip() for origin in os.getenv("ALLOWED_ORIGINS", "*").split(",") if origin.strip()]
# APP_MODE: heavy(默认)、lite 或 standard
APP_MODE = os.getenv("APP_MODE", "heavy").lower().strip()
def is_lite_mode() -> bool:
return APP_MODE == "lite"
def is_standard_mode() -> bool:
"""Standard 模式:发送完整上下文,支持 thinking 和搜索输出"""
return APP_MODE == "standard"
def get_default_account():
"""获取默认账号(列表中的第一个账号)"""
return ACCOUNTS[0]
+2115
View File
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
import os
from slowapi import Limiter
from slowapi.util import get_remote_address
from app.config import is_lite_mode, is_standard_mode
# DISABLE_RATE_LIMIT=True 时关闭限流(调试用)
_disable_flag = os.getenv("DISABLE_RATE_LIMIT", "").strip().lower()
_rate_limit_disabled = _disable_flag == "true"
# 根据 APP_MODE 动态设置速率限制
# Lite 模式:30/minute(单轮问答响应快,3-5秒/次)
# Standard 模式:25/minute(完整上下文,支持 thinking 和搜索)
# Heavy 模式:20/minute(需要数据库操作,相对慢一些)
if is_lite_mode():
default_limit = "30/minute"
elif is_standard_mode():
default_limit = "25/minute"
else:
default_limit = "20/minute"
limiter = Limiter(
key_func=get_remote_address,
default_limits=[] if _rate_limit_disabled else [default_limit],
enabled=not _rate_limit_disabled,
)
+41
View File
@@ -0,0 +1,41 @@
import logging
import json
import time
from datetime import datetime
class JsonFormatter(logging.Formatter):
"""自定义 JSON 格式化器"""
def format(self, record):
log_record = {
"timestamp": datetime.fromtimestamp(record.created).isoformat(),
"level": record.levelname,
"message": record.getMessage(),
}
# 提取自定义 extra 字段
if hasattr(record, "request_info"):
log_record.update(record.request_info)
# 如果有异常,记录 trace
if record.exc_info:
log_record["exception"] = self.formatException(record.exc_info)
return json.dumps(log_record, ensure_ascii=False)
def setup_logger(name="notion_opus"):
"""配置并返回单例全局 logger"""
logger = logging.getLogger(name)
# 防止重复添加 handler
if not logger.handlers:
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setFormatter(JsonFormatter())
logger.addHandler(console_handler)
return logger
# 全局单例 logger 实例
logger = setup_logger()
+138
View File
@@ -0,0 +1,138 @@
MODEL_MAP: dict[str, str] = {
"gpt-5.6-sol": "orange-mousse",
"gpt-5.6-terra": "orchid-muffin",
"gpt-5.6-luna": "olive-jellyroll",
"gpt-5.4": "oval-kumquat-medium",
"gpt-5.5": "opal-quince-medium",
"gemini-3.5flash": "vertex-gemini-3.5-flash",
"claude-sonnet4.6": "almond-croissant-low",
"claude-sonnet5": "angel-cake-high",
"claude-opus4.6": "avocado-froyo-medium",
"claude-opus4.7": "apricot-sorbet-high",
"claude-opus4.8": "ambrosia-tart-high",
"claude-opus5": "agave-flan",
"kimi-2.7": "fireworks-kimi-k2.7",
"deepseek-v4pro": "baseten-deepseek-v4-pro",
"glm-5.2": "baseten-glm-5.2",
"grok-4.3": "xigua-mochi-medium",
"spacexai-4.5": "strawberry-whoopiepie",
"grok-build0.1": "xinomavro-cake",
"gemini-3.1pro": "galette-medium-thinking",
"claude-haiku4.5": "anthropic-haiku-4.5",
"fable-5": "acai-budino-high",
"gemini-3flash": "gingerbread",
"gpt-6-astra": "orlando-quinn",
}
NOTION_MODEL_REVERSE_MAP: dict[str, str] = {value: key for key, value in MODEL_MAP.items()}
DISPLAY_NAMES: dict[str, str] = {
"gpt-5.6-sol": "GPT-5.6 Sol",
"gpt-5.6-terra": "GPT-5.6 Terra",
"gpt-5.6-luna": "GPT-5.6 Luna",
"gpt-5.4": "GPT-5.4",
"gpt-5.5": "GPT-5.5",
"gemini-3.5flash": "Gemini 3.5 Flash",
"claude-sonnet4.6": "Sonnet 4.6",
"claude-sonnet5": "Sonnet 5",
"claude-opus4.6": "Opus 4.6",
"claude-opus4.7": "Opus 4.7",
"claude-opus4.8": "Opus 4.8",
"claude-opus5": "Opus 5",
"kimi-2.7": "Kimi K2.7 Code",
"deepseek-v4pro": "DeepSeek V4 Pro",
"glm-5.2": "GLM 5.2",
"grok-4.3": "Grok 4.3",
"spacexai-4.5": "SpaceXAI 4.5",
"grok-build0.1": "Grok Build 0.1",
"gemini-3.1pro": "Gemini 3.1 Pro",
"claude-haiku4.5": "Haiku 4.5",
"fable-5": "Fable 5",
"gemini-3flash": "Gemini 3 Flash",
"gpt-6-astra": "GPT-6 Astra",
}
MODEL_ICONS: dict[str, str] = {
"gpt-5.6-sol": "⚙",
"gpt-5.6-terra": "⚙",
"gpt-5.6-luna": "⚙",
"gpt-5.4": "⚙",
"gpt-5.5": "⚙",
"gemini-3.5flash": "✦",
"claude-sonnet4.6": "✳️",
"claude-sonnet5": "✳️",
"claude-opus4.6": "✳️",
"claude-opus4.7": "✳️",
"claude-opus4.8": "✳️",
"claude-opus5": "✳️",
"kimi-2.7": "🌙",
"deepseek-v4pro": "🐋",
"glm-5.2": "◆",
"grok-4.3": "⚡",
"spacexai-4.5": "⚡",
"grok-build0.1": "⚡",
"gemini-3.1pro": "✦",
"claude-haiku4.5": "✳️",
"fable-5": "◇",
"gemini-3flash": "✦",
"gpt-6-astra": "⚙",
}
# 默认使用 Sonnet 4.6(速度和质量的最佳平衡)
DEFAULT_MODEL = "claude-sonnet4.6"
def get_notion_model(model_name: str) -> str:
return MODEL_MAP.get(model_name, MODEL_MAP[DEFAULT_MODEL])
# 需要走 markdown-chat 的 Notion 内部代号(vertex- 前缀的模型)
# Gemini 3.1 Pro (galette-medium-thinking) 已改为 workflow,不再走 markdown-chat
MARKDOWN_CHAT_MODELS: set[str] = {
"vertex-gemini-3.5-flash",
}
def is_gemini_model(model_name: str) -> bool:
"""判断是否为 Gemini 系列模型(用于 config block 构建等)"""
standard_name = get_standard_model(model_name)
if standard_name.startswith("gemini-"):
return True
notion_model = get_notion_model(standard_name)
return notion_model.startswith("vertex-") or notion_model.startswith("galette-")
def get_thread_type(model_name: str) -> str:
"""
根据模型确定 Notion thread type。
只有 vertex- 前缀的模型走 markdown-chat,其余全部走 workflow。
"""
standard_name = get_standard_model(model_name)
notion_model = get_notion_model(standard_name)
if notion_model in MARKDOWN_CHAT_MODELS:
return "markdown-chat"
return "workflow"
def get_standard_model(model_name: str) -> str:
if model_name in MODEL_MAP:
return model_name
return NOTION_MODEL_REVERSE_MAP.get(model_name, DEFAULT_MODEL)
def list_available_models() -> list[str]:
return list(MODEL_MAP.keys())
def is_supported_model(model_name: str) -> bool:
return model_name in MODEL_MAP
def get_display_name(model_name: str) -> str:
standard_name = get_standard_model(model_name)
return DISPLAY_NAMES.get(standard_name, standard_name)
def get_model_icon(model_name: str) -> str:
standard_name = get_standard_model(model_name)
return MODEL_ICONS.get(standard_name, "")
+410
View File
@@ -0,0 +1,410 @@
import os
import threading
import time
import uuid
from typing import Any, Generator, Optional
import cloudscraper
import requests
import urllib3
from app.logger import logger
from app.model_registry import get_notion_model
from app.stream_parser import parse_stream
# 禁用 SSL 警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 可通过环境变量覆盖 Notion 客户端版本号(Notion 更新后可能需要同步)
NOTION_CLIENT_VERSION = os.getenv("NOTION_CLIENT_VERSION", "23.13.20260228.0625")
# Notion 站点根地址(区域镜像 / 反代时可覆盖);未设置时保持官方默认
NOTION_URL = os.getenv("NOTION_URL", "https://www.notion.so").rstrip("/")
class NotionUpstreamError(RuntimeError):
"""Notion 上游请求失败或返回异常内容。"""
def __init__(
self,
message: str,
*,
status_code: Optional[int] = None,
retriable: bool = True,
response_excerpt: str = "",
):
super().__init__(message)
self.status_code = status_code
self.retriable = retriable
self.response_excerpt = response_excerpt
class NotionOpusAPI:
def __init__(self, account_config: dict):
"""
从单组账号配置初始化 Notion 客户端。
account_config 需要包含 token_v2, space_id, user_id, space_view_id, user_name, user_email
"""
self.token_v2 = account_config.get("token_v2", "")
self.space_id = account_config.get("space_id", "")
self.user_id = account_config.get("user_id", "")
self.space_view_id = account_config.get("space_view_id", "")
self.user_name = account_config.get("user_name", "user")
self.user_email = account_config.get("user_email", "")
self.cookies = account_config.get("cookies", {})
if not isinstance(self.cookies, dict):
self.cookies = {}
self.cookies["token_v2"] = self.token_v2
self.url = f"{NOTION_URL}/api/v3/runInferenceTranscript"
self.delete_url = f"{NOTION_URL}/api/v3/saveTransactions"
self.account_key = self.user_email or self.user_id or "unknown-account"
# 复用 cloudscraper 实例:保留 Cloudflare challenge cookie,避免每次请求都重新过验证
self._scraper = cloudscraper.create_scraper()
self._scraper_lock = threading.Lock()
def _build_cookie_header(self) -> str:
cookie_jar = self.cookies.copy()
cookie_jar["notion_user_id"] = self.user_id
return "; ".join(f"{name}={value}" for name, value in cookie_jar.items() if value)
def _to_notion_transcript(self, transcript: list[dict[str, Any]]) -> list[dict[str, Any]]:
converted: list[dict[str, Any]] = []
for block in transcript:
if block.get("type") != "config":
converted.append(block)
continue
value = block.get("value")
if not isinstance(value, dict):
converted.append(block)
continue
notion_block = dict(block)
notion_value = dict(value)
notion_value["model"] = get_notion_model(str(value.get("model", "") or ""))
notion_block["value"] = notion_value
converted.append(notion_block)
return converted
def _resolve_thread_type(self, notion_transcript: list[dict[str, Any]]) -> str:
for block in notion_transcript:
if block.get("type") != "config":
continue
value = block.get("value")
if isinstance(value, dict):
thread_type = str(value.get("type", "") or "").strip()
if thread_type:
return thread_type
return "workflow"
def _resolve_request_profile(self, thread_type: str) -> dict[str, Any]:
is_markdown_chat = thread_type == "markdown-chat"
return {
"thread_type": thread_type,
"create_thread": not is_markdown_chat,
"is_partial_transcript": is_markdown_chat,
"precreate_thread": is_markdown_chat,
"include_debug_overrides": True,
}
def _build_thread_headers(self) -> dict[str, str]:
return {
"content-type": "application/json",
"cookie": self._build_cookie_header(),
"x-notion-active-user-header": self.user_id,
"x-notion-space-id": self.space_id,
}
def _create_thread(self, thread_id: str, thread_type: str) -> bool:
payload = {
"requestId": str(uuid.uuid4()),
"transactions": [
{
"id": str(uuid.uuid4()),
"spaceId": self.space_id,
"operations": [
{
"pointer": {"table": "thread", "id": thread_id, "spaceId": self.space_id},
"path": [],
"command": "set",
"args": {
"id": thread_id,
"version": 1,
"parent_id": self.space_id,
"parent_table": "space",
"space_id": self.space_id,
"created_time": int(time.time() * 1000),
"created_by_id": self.user_id,
"created_by_table": "notion_user",
"messages": [],
"data": {},
"alive": True,
"type": thread_type,
},
}
],
}
],
}
try:
resp = requests.post(
self.delete_url,
json=payload,
headers=self._build_thread_headers(),
timeout=20,
)
if resp.status_code == 200:
return True
logger.warning(
"Pre-create thread failed",
extra={
"request_info": {
"event": "thread_precreate_failed",
"thread_id": thread_id,
"thread_type": thread_type,
"status": resp.status_code,
}
},
)
except Exception:
logger.warning(
"Pre-create thread raised exception",
exc_info=True,
extra={
"request_info": {
"event": "thread_precreate_error",
"thread_id": thread_id,
"thread_type": thread_type,
}
},
)
return False
def delete_thread(self, thread_id: str) -> None:
"""
通过 saveTransactions 接口将指定 thread 的 alive 状态设为 False,
从而清理 Notion 主页面上的对话记录。
此方法设计为在后台线程中调用,不影响主流输出。
"""
headers = self._build_thread_headers()
payload = {
"requestId": str(uuid.uuid4()),
"transactions": [
{
"id": str(uuid.uuid4()),
"spaceId": self.space_id,
"operations": [
{
"pointer": {
"table": "thread",
"id": thread_id,
"spaceId": self.space_id,
},
"command": "update",
"path": [],
"args": {"alive": False},
}
],
}
],
}
try:
resp = requests.post(self.delete_url, json=payload, headers=headers, timeout=15)
if resp.status_code == 200:
logger.info(
"Thread auto-deleted from Notion home",
extra={"request_info": {"event": "thread_deleted", "thread_id": thread_id}},
)
else:
logger.warning(
f"Thread deletion failed: HTTP {resp.status_code}",
extra={"request_info": {"event": "thread_delete_failed", "thread_id": thread_id, "status": resp.status_code}},
)
except Exception as exc:
logger.warning(
f"Thread deletion raised an exception: {exc}",
extra={"request_info": {"event": "thread_delete_error", "thread_id": thread_id}},
)
def stream_response(self, transcript: list, thread_id: Optional[str] = None) -> Generator[dict[str, Any], None, None]:
"""
发起 Notion API 请求并返回结构化流生成器。
接收完整的 transcript 列表作为参数。
Args:
transcript: 对话历史记录列表
thread_id: 可选的已有 thread_id。如果提供,将重用该线程以保持上下文
"""
if not isinstance(transcript, list) or not transcript:
raise ValueError("Invalid transcript payload: transcript must be a non-empty list.")
notion_transcript = self._to_notion_transcript(transcript)
thread_type = self._resolve_thread_type(notion_transcript)
request_profile = self._resolve_request_profile(thread_type)
# 如果没有提供 thread_id,创建新的;否则重用已有的
should_create_thread = thread_id is None
thread_id = thread_id or str(uuid.uuid4())
trace_id = str(uuid.uuid4())
response = None
# 保存 thread_id 以便外部访问
self.current_thread_id = thread_id
if request_profile["precreate_thread"] and should_create_thread:
if not self._create_thread(thread_id, thread_type):
should_create_thread = True
request_profile["create_thread"] = True
request_profile["is_partial_transcript"] = False
elif not should_create_thread:
# 如果重用已有线程,不要创建新线程
request_profile["create_thread"] = False
# 关键修复:设置 is_partial_transcript=True,让 Notion 接受客户端的历史消息
request_profile["is_partial_transcript"] = True
# 把 cookie 直接放进 header,绕过 cloudscraper 的 cookie jar
# (cookie jar 可能被 Cloudflare challenge 写入含非 ASCII 字符的 cookie,导致编码错误)
cookie_header = self._build_cookie_header()
# ВАЖНО (2026-09-06): апстрим отдаёт пустой стрим без браузерного фингерпринта
# (проверено A/B: те же payload/token/IP — с sec-fetch + свежим UA идёт NDJSON, без них пусто).
headers = {
"Content-Type": "application/json",
"Accept": "application/x-ndjson",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36",
"x-notion-space-id": self.space_id,
"x-notion-active-user-header": self.user_id,
"notion-audit-log-platform": "web",
"notion-client-version": NOTION_CLIENT_VERSION,
"origin": NOTION_URL,
"referer": f"{NOTION_URL}/chat",
"sec-ch-ua": '"Chromium";v="152", "Not?A_Brand";v="24", "Google Chrome";v="152"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Linux"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"cookie": cookie_header,
}
payload = {
"traceId": trace_id,
"spaceId": self.space_id,
"threadId": thread_id,
"threadType": thread_type,
"createThread": request_profile["create_thread"],
"generateTitle": True,
"saveAllThreadOperations": True,
"setUnreadState": True,
"isPartialTranscript": request_profile["is_partial_transcript"],
"asPatchResponse": True,
"isUserInAnySalesAssistedSpace": False,
"isSpaceSalesAssisted": False,
"threadParentPointer": {
"table": "space",
"id": self.space_id,
"spaceId": self.space_id,
},
"transcript": notion_transcript,
}
if request_profile["include_debug_overrides"]:
payload["debugOverrides"] = {
"emitAgentSearchExtractedResults": True,
"cachedInferences": {},
"annotationInferences": {},
"emitInferences": False,
}
logger.info(
"Dispatching request to Notion upstream",
extra={
"request_info": {
"event": "notion_upstream_request",
"trace_id": trace_id,
"thread_id": thread_id,
"thread_type": thread_type,
"create_thread": bool(request_profile["create_thread"]),
"is_partial_transcript": bool(request_profile["is_partial_transcript"]),
"account": self.account_key,
"space_id": self.space_id,
}
},
)
try:
with self._scraper_lock:
scraper = self._scraper
scraper.cookies.clear()
response = scraper.post(
self.url,
headers=headers,
json=payload,
stream=True,
timeout=(15, 120),
)
if response.status_code == 403:
# Cloudflare challenge 可能过期,重建 scraper 后重试一次
response.close()
logger.warning(
"Got 403, rebuilding cloudscraper to refresh Cloudflare challenge",
extra={"request_info": {"event": "cloudflare_challenge_refresh", "account": self.account_key}},
)
new_scraper = cloudscraper.create_scraper()
with self._scraper_lock:
self._scraper = new_scraper
response = new_scraper.post(
self.url,
headers=headers,
json=payload,
stream=True,
timeout=(15, 120),
)
if response.status_code != 200:
excerpt = (response.text or "").strip().replace("\n", " ")[:300]
# 429 和 5xx 都允许重试(换账号或等待后重试)
retriable = response.status_code >= 500 or response.status_code == 429
raise NotionUpstreamError(
f"Notion upstream returned HTTP {response.status_code}.",
status_code=response.status_code,
retriable=retriable,
response_excerpt=excerpt,
)
emitted = False
for chunk in parse_stream(response):
emitted = True
yield chunk
if not emitted:
raise NotionUpstreamError(
"Notion upstream returned an empty stream.",
status_code=502,
retriable=True,
)
# 流结束后,不再自动删除 thread
# 原因:Notion API 的 workflow 模式依赖于服务器端保存的对话历史
# 删除 thread 会导致后续请求无法获取历史消息(AI 失忆)
# 保持 thread 存活可以维持对话上下文
logger.info(
"Thread completed and preserved for conversation context",
extra={
"request_info": {
"event": "thread_completed_preserved",
"thread_id": thread_id,
"was_created_new": should_create_thread,
}
},
)
except requests.exceptions.Timeout as exc:
logger.error(f"Request timeout: {exc}", exc_info=True)
raise NotionUpstreamError("Request to Notion upstream timed out.", retriable=True) from exc
except requests.exceptions.RequestException as exc:
logger.error(f"Request failed: {exc}", exc_info=True)
# 不暴露原始异常细节给用户
raise NotionUpstreamError("Request to Notion upstream failed. Please try again later.", retriable=True) from exc
finally:
if response is not None:
response.close()
+93
View File
@@ -0,0 +1,93 @@
import time
from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, Field, field_validator
# ================================
# 请求相关 Schema (Chat Completion)
# ================================
class ChatMessage(BaseModel):
"""单条对话消息"""
role: Literal["user", "assistant", "system"]
content: str
thinking: Optional[str] = None
@field_validator("content", mode="before")
@classmethod
def _coerce_content_parts(cls, v):
# OpenAI-style content parts (отправляют omp и др. клиенты) → plain text.
# Не-текстовые части (image_url и т.п.) мост не поддерживает и молча отбрасывает.
if v is None:
return ""
if isinstance(v, str):
return v
if isinstance(v, list):
texts = []
for part in v:
if isinstance(part, dict) and part.get("type") == "text":
texts.append(part.get("text") or "")
elif isinstance(part, str):
texts.append(part)
return "".join(texts)
return str(v)
class ChatCompletionRequest(BaseModel):
"""
OpenAI-Compatible 发起完成请求的 Payload。
保留 `conversation_id` 作为特定的扩展字段,若缺失则视为独立请求。
"""
model: str = Field(default="claude-opus4.6", description="Requested model.")
messages: List[ChatMessage]
stream: bool = Field(default=False, description="Whether to stream the response as SSE.")
temperature: Optional[float] = Field(default=None, description="Sampling temperature.")
conversation_id: Optional[str] = Field(default=None, description="Extension for stateful conversation tracking.")
# ================================
# 非流式返回 Schema
# ================================
class ChatMessageResponseChoice(BaseModel):
"""非流式响应的选项"""
index: int = 0
message: ChatMessage
finish_reason: str = "stop"
class ChatCompletionResponse(BaseModel):
"""
OpenAI-Compatible 完整返回 Payload。
"""
id: str
object: str = "chat.completion"
created: int = Field(default_factory=lambda: int(time.time()))
model: str
choices: List[ChatMessageResponseChoice]
usage: Dict[str, int] = Field(
default_factory=lambda: {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
)
# Standard 模式扩展字段
search_metadata: Optional[Dict[str, Any]] = Field(default=None)
# ================================
# 流式返回 Schema (供内部组织)
# ================================
class ChatCompletionChunkDelta(BaseModel):
"""SSE Delta Block"""
content: Optional[str] = None
role: Optional[str] = None
class ChatCompletionChunkChoice(BaseModel):
"""SSE Choice Block"""
index: int = 0
delta: ChatCompletionChunkDelta
finish_reason: Optional[str] = None
class ChatCompletionChunk(BaseModel):
"""
OpenAI-Compatible 流式 Chunk
"""
id: str
object: str = "chat.completion.chunk"
created: int = Field(default_factory=lambda: int(time.time()))
model: str
choices: List[ChatCompletionChunkChoice]
+172
View File
@@ -0,0 +1,172 @@
import time
import os
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from slowapi.errors import RateLimitExceeded
from contextlib import asynccontextmanager
from app.config import ACCOUNTS, API_KEY, ALLOWED_ORIGINS, is_lite_mode, is_standard_mode
from app.account_pool import AccountPool
from app.conversation import ConversationManager
from app.api.chat import router as chat_router
from app.api.models import router as models_router
from app.logger import logger
from app.limiter import limiter
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时初始化状态
app.state.account_pool = AccountPool(ACCOUNTS)
# 确定运行模式
if is_lite_mode():
mode = "lite"
logger.info("Service starting up in LITE mode", extra={"request_info": {"event": "startup", "accounts": len(ACCOUNTS), "mode": "lite"}})
elif is_standard_mode():
mode = "standard"
logger.info("Service starting up in STANDARD mode", extra={"request_info": {"event": "startup", "accounts": len(ACCOUNTS), "mode": "standard"}})
else:
mode = "heavy"
app.state.conversation_manager = ConversationManager()
logger.info("Service starting up in HEAVY mode", extra={"request_info": {"event": "startup", "accounts": len(ACCOUNTS), "mode": "heavy"}})
app.state.start_time = time.time()
yield
# 关闭时清理
logger.info("Service shutting down", extra={"request_info": {"event": "shutdown"}})
app = FastAPI(
title="Notion Opus API",
description="A FastAPI wrapper providing an OpenAI-compatible interface for Notion's Claude Opus backend.",
version="1.0.0",
lifespan=lifespan
)
# 允许跨域(配合本地前端)
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 注入 Limiter
app.state.limiter = limiter
# 自定义 429 速率限制响应
def custom_rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded):
return JSONResponse(
status_code=429,
content={"error": "Too many requests, please try again later"}
)
app.add_exception_handler(RateLimitExceeded, custom_rate_limit_exceeded_handler)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
logger.error(
"Unhandled application exception",
exc_info=True,
extra={
"request_info": {
"event": "unhandled_exception",
"method": request.method,
"path": request.url.path,
}
},
)
return JSONResponse(
status_code=500,
content={
"error": {
"message": "Internal server error",
"type": "server_error",
}
},
)
# 结构化日志中间件
@app.middleware("http")
async def log_requests_middleware(request: Request, call_next):
start_time = time.time()
# 跳过高频且不重要的日志打印,避免刷屏
skip_logging = request.url.path in ["/health", "/favicon.ico"]
try:
response = await call_next(request)
status_code = response.status_code
except Exception as e:
status_code = 500
logger.error(f"Unhandled exception: {str(e)}", exc_info=True)
raise
finally:
process_time = time.time() - start_time
client_ip = request.client.host if request.client else "unknown"
if not skip_logging:
log_level = logger.error if status_code >= 400 else logger.info
log_level(
"Request processed",
extra={
"request_info": {
"method": request.method,
"path": request.url.path,
"ip": client_ip,
"status_code": status_code,
"duration_ms": round(process_time * 1000, 2)
}
}
)
return response
# 简易 API Key 鉴权中间件
@app.middleware("http")
async def api_key_auth(request: Request, call_next):
# 如果环境配置中未设置 API_KEY,则全局不验证
if API_KEY:
# 跳过 OPTIONS 请求和非受保护的静态路由(如果以后有的话)
if request.url.path.startswith("/v1") and request.method != "OPTIONS":
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer ") or auth_header.split(" ")[1] != API_KEY:
return JSONResponse(
status_code=401,
content={
"error": {
"message": "Error: API KEY doesn't match.",
"type": "invalid_request_error",
"code": "invalid_api_key"
}
}
)
return await call_next(request)
# 挂载路由,前缀统一为 /v1
app.include_router(chat_router, prefix="/v1")
app.include_router(models_router, prefix="/v1")
# 挂载健康检查
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
return Response(content=b"", media_type="image/x-icon", status_code=204)
@app.get("/health", tags=["system"])
def health_check(request: Request):
uptime = time.time() - request.app.state.start_time
pool = request.app.state.account_pool
status = pool.get_status_summary()
return {
"status": "ok",
"accounts": status["active"],
"accounts_total": status["total"],
"accounts_cooling": status["cooling"],
"uptime": int(uptime)
}
# 挂载静态前端到根目录
frontend_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "frontend")
if os.path.exists(frontend_dir):
app.mount("/", StaticFiles(directory=frontend_dir, html=True), name="frontend")
+1013
View File
File diff suppressed because it is too large Load Diff
+93
View File
@@ -0,0 +1,93 @@
import httpx
from app.config import SILICONFLOW_API_KEY
class SummarizerUnavailableError(Exception):
"""Raised when summarizer service cannot be used."""
SILICONFLOW_ENDPOINT = "https://api.siliconflow.cn/v1/chat/completions"
MODEL_FALLBACK_CHAIN = ["Qwen/Qwen3-8B", "THUDM/glm-4-9b-chat"]
SYSTEM_PROMPT = (
"你是一个对话摘要助手。请将用户提供的一轮对话(一问一答)压缩成1~3句话的简洁摘要。\n"
"要求:保留关键信息(话题、结论、重要细节),去除废话,语言简洁,使用与对话相同的语言。\n\n"
"只输出摘要本身,不要有任何前缀或解释。"
)
def is_summarizer_configured() -> bool:
return bool(SILICONFLOW_API_KEY.strip())
def _build_user_prompt(old_summaries: list[str], user_msg: str, assistant_msg: str) -> str:
prompt_parts = []
if old_summaries:
prompt_parts.append("【已有上下文摘要(仅供参考,勿重复)】")
prompt_parts.append("\n".join(old_summaries[-5:]))
prompt_parts.append("")
prompt_parts.append("【本轮对话】")
prompt_parts.append(f"用户:{user_msg}")
prompt_parts.append(f"AI:{assistant_msg}")
prompt_parts.append("")
prompt_parts.append("请输出本轮摘要:")
return "\n".join(prompt_parts)
async def _call_summarizer(model: str, old_summaries: list[str], user_msg: str, assistant_msg: str) -> str:
timeout = httpx.Timeout(connect=5.0, read=20.0, write=20.0, pool=20.0)
headers = {
"Authorization": f"Bearer {SILICONFLOW_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": model,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": _build_user_prompt(old_summaries, user_msg, assistant_msg)},
],
"temperature": 0.2,
}
async with httpx.AsyncClient(timeout=timeout) as client:
response = await client.post(SILICONFLOW_ENDPOINT, headers=headers, json=payload)
if response.status_code != 200:
raise SummarizerUnavailableError(f"Summarizer upstream returned status {response.status_code}")
data = response.json()
content = (
data.get("choices", [{}])[0]
.get("message", {})
.get("content", "")
)
summary = str(content).strip()
if not summary:
raise SummarizerUnavailableError("Summarizer returned empty summary")
return summary
async def summarize_turn(
old_summaries: list[str],
user_msg: str,
assistant_msg: str,
) -> str:
"""
调用 LLM 将一轮对话压缩为简短摘要,返回摘要字符串。失败时抛出异常。
"""
if not is_summarizer_configured():
raise SummarizerUnavailableError("SILICONFLOW_API_KEY is empty")
last_error: Exception | None = None
for model in MODEL_FALLBACK_CHAIN:
try:
return await _call_summarizer(model, old_summaries, user_msg, assistant_msg)
except Exception as exc:
last_error = exc
continue
raise SummarizerUnavailableError(
f"All summarizer models failed: {last_error}"
) from last_error