#!/usr/bin/env python """API 模块 定义 Connexion 应用和 API 函数,供 server.yaml 引用。 """ import os from workaround_env_fix import diagnose_and_fix_thread_env_vars # 放此处:server 为应用入口(run.py 或 gunicorn 均会加载),须在 import connexion/backend 前执行 diagnose_and_fix_thread_env_vars() os.environ["TOKENIZERS_PARALLELISM"] = "false" import warnings warnings.filterwarnings( "ignore", message=r"Using `httpx` with `starlette\.testclient`", category=UserWarning, ) import connexion from connexion.datastructures import MediaTypeDict from connexion.exceptions import BadRequestProblem from connexion.validators import JSONRequestBodyValidator, VALIDATOR_MAP from backend.platform.logging_config import configure_logging from backend.api.static import register_static_routes from backend.platform.visit_stats import register_visit_stats # 导入 API 函数供 server.yaml 使用 from backend.api.analyze import analyze # noqa: F401 from backend.api.demo import ( # noqa: F401 list_demos, save_demo, delete_demo, move_demo, rename_demo, check_admin, ) from backend.api.folder import ( # noqa: F401 rename_folder_api as rename_folder, delete_folder_api as delete_folder, list_all_folders, create_folder_api, ) from backend.api.fetch_url import fetch_url # noqa: F401 from backend.api.client_activity import client_activity_report # noqa: F401 from backend.api.extension_usage import extension_usage_report # noqa: F401 from backend.api.analyze_semantic import ( # noqa: F401 analyze_semantic, analyze_semantic_relevance, analyze_semantic_keywords, ) from backend.api.prediction_attribute import prediction_attribute # noqa: F401 from backend.api.tokenize import tokenize # noqa: F401 from backend.api.model_switch import ( # noqa: F401 get_available_models, get_current_model, switch_model, ) from backend.api.visit_stats_api import ( # noqa: F401 get_visit_stats, get_visit_stats_active_visits_timeline, post_visit_stats_reset, ) from backend.api.health import health # noqa: F401 from backend.api.openai_completions import ( # noqa: F401 completions, completions_prompt, completions_prompt_incremental, completions_stop, ) from backend.core.completion_generator import register_inference_shutdown_handlers register_inference_shutdown_handlers() class _JSONRequestBodyValidator(JSONRequestBodyValidator): """非法编码的 JSON 体是 400,不要让 Connexion 的 utf-8 decode 变成 500。""" async def _parse(self, stream, scope): try: return await super()._parse(stream, scope) except UnicodeDecodeError as exc: raise BadRequestProblem( detail=f"Request body is not valid {self._encoding}: {exc}" ) from exc _json_body_validators = MediaTypeDict(dict(VALIDATOR_MAP["body"])) _json_body_validators["*/*json"] = _JSONRequestBodyValidator # 创建 Connexion 应用 app = connexion.App(__name__) # 配置日志 configure_logging(app) register_visit_stats(app) # 注册路由 register_static_routes(app) app.add_api("server.yaml", validator_map={"body": _json_body_validators}) def _log_500_handler(request, exc): """未捕获异常时打印完整 traceback 到 stdout,便于 Docker 日志排查""" import traceback from connexion.problem import problem # 只处理非 HTTP 异常(404/400 等应保持原状态码) if hasattr(exc, 'status_code') and 400 <= getattr(exc, 'status_code', 0) < 500: raise exc print("=" * 60) print("❌ 500 Internal Server Error") if exc is not None: traceback.print_exception(type(exc), exc, exc.__traceback__) else: print("(no exception object passed to error handler)") print("=" * 60) return problem( status=500, title="Internal Server Error", detail=str(exc) if exc is not None else "Internal Server Error", ) app.add_error_handler(Exception, _log_500_handler)