You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.7 KiB
Python

import sys
import traceback
from lib.config import Config
from utils.server import get_server_modules
Config.load_config("config.toml")
from utils.local import loop, noawait
from aiohttp import web
import utils.local as local
import server.route as api_route
import utils.web
from service.mediawiki_api import MediaWikiApi
async def index(request: web.Request):
return await utils.web.api_response(
1, data={"message": "Isekai toolkit API"}, request=request
)
@web.middleware
async def error_handler(request, handler):
try:
response = await handler(request)
return response
except utils.web.ParamInvalidException as ex:
return await utils.web.api_response(
-1,
error={"code": "invalid-params", "message": "Invalid params.", "invalid_params": ex.param_list},
http_status=400,
request=request,
)
except web.HTTPException as ex:
return await utils.web.api_response(
-1,
error={"code": f"http_{ex.status}", "message": ex.reason},
http_status=ex.status,
request=request,
)
except Exception as ex:
error_id = utils.web.generate_uuid()
err_msg = f"Server error [{error_id}]: {ex}"
print(err_msg, file=sys.stderr)
traceback.print_exc()
print(f"End of error [{error_id}]", file=sys.stderr)
return await utils.web.api_response(
-1,
error={"code": "internal-server-error", "message": err_msg},
http_status=500,
request=request,
)
async def stop_noawait_pool(app: web.Application):
await noawait.end()
if __name__ == "__main__":
local.debug = Config.get("server.debug", False, bool)
app = web.Application(
middlewares=[
error_handler,
]
)
import init.server.base_api as _
# Dynamically import modules
if Config.get("toolbox_ui.enable"):
import init.server.toolbox_ui as _
if Config.get("embedding.enable"):
import init.server.embedding_search as _
if Config.get("chatcomplete.enable"):
import init.server.chat_complete as _
# Initialize server modules
server_modules = get_server_modules()
print(server_modules)
for server_module in server_modules:
server_module["init"](app)
app.on_shutdown.append(stop_noawait_pool)
app.router.add_route("*", "/", index)
api_route.init(app)
server_port = Config.get("port", 8144, int)
web.run_app(
app,
host="0.0.0.0",
port=server_port,
loop=loop,
)