local-llm-server/server.py

178 lines
6.4 KiB
Python
Raw Normal View History

from llm_server.config.config import mode_ui_names
2023-09-26 22:09:11 -06:00
try:
import gevent.monkey
gevent.monkey.patch_all()
except ImportError:
pass
from llm_server.pre_fork import server_startup
from llm_server.config.load import load_config
2023-08-21 21:28:52 -06:00
import os
import sys
from pathlib import Path
2023-09-23 21:17:13 -06:00
import simplejson as json
2023-08-23 23:11:12 -06:00
from flask import Flask, jsonify, render_template, request
2023-08-21 21:28:52 -06:00
import llm_server
from llm_server.database.conn import database
from llm_server.database.create import create_db
from llm_server.llm import get_token_count
2023-09-12 16:40:09 -06:00
from llm_server.routes.openai import openai_bp
from llm_server.routes.server_error import handle_server_error
2023-09-26 13:32:33 -06:00
from llm_server.routes.v1 import bp
from llm_server.stream import init_socketio
2023-09-27 14:36:49 -06:00
# TODO: have the workers handle streaming too
2023-09-27 16:12:36 -06:00
# TODO: add backend fallbacks. Backends at the bottom of the list are higher priority and are fallbacks if the upper ones fail
# TODO: implement background thread to test backends via sending test prompts
# TODO: if backend fails request, mark it as down
2023-09-26 22:09:11 -06:00
# TODO: allow setting concurrent gens per-backend
2023-09-27 16:12:36 -06:00
# TODO: set the max tokens to that of the lowest backend
# TODO: implement RRD backend loadbalancer option
2023-09-27 19:39:04 -06:00
# TODO: have VLLM reject a request if it already has n == concurrent_gens running
# TODO: add a way to cancel VLLM gens. Maybe use websockets?
# TODO: use coloredlogs
# Lower priority
# TODO: the processing stat showed -1 and I had to restart the server
2023-09-27 14:36:49 -06:00
# TODO: simulate OpenAI error messages regardless of endpoint
2023-09-27 16:12:36 -06:00
# TODO: send extra headers when ratelimited?
2023-09-25 18:18:29 -06:00
# TODO: make sure log_prompt() is used everywhere, including errors and invalid requests
# TODO: unify logging thread in a function and use async/await instead
# TODO: move the netdata stats to a seperate part of the stats and have it set to the currently selected backend
# TODO: have VLLM reply with stats (TPS, generated token count, processing time)
# TODO: add config reloading via stored redis variables
2023-09-27 16:12:36 -06:00
# Done, but need to verify
# TODO: add more excluding to SYSTEM__ tokens
# TODO: return 200 when returning formatted sillytavern error
2023-09-12 01:05:03 -06:00
try:
import vllm
except ModuleNotFoundError as e:
print('Could not import vllm-gptq:', e)
2023-09-12 01:10:58 -06:00
print('Please see README.md for install instructions.')
2023-09-12 01:05:03 -06:00
sys.exit(1)
2023-08-23 23:11:12 -06:00
import config
2023-08-21 21:28:52 -06:00
from llm_server import opts
from llm_server.helpers import auto_set_base_client_api
from llm_server.llm.vllm.info import vllm_info
2023-09-26 22:09:11 -06:00
from llm_server.routes.cache import RedisWrapper, flask_cache
from llm_server.llm import redis
from llm_server.routes.stats import get_active_gen_workers
2023-08-23 23:11:12 -06:00
from llm_server.routes.v1.generate_stats import generate_stats
2023-08-21 23:07:12 -06:00
2023-09-26 13:32:33 -06:00
app = Flask(__name__)
init_socketio(app)
app.register_blueprint(bp, url_prefix='/api/v1/')
app.register_blueprint(openai_bp, url_prefix='/api/openai/v1/')
2023-09-26 22:09:11 -06:00
flask_cache.init_app(app)
flask_cache.clear()
2023-09-26 13:32:33 -06:00
script_path = os.path.dirname(os.path.realpath(__file__))
2023-08-21 21:28:52 -06:00
config_path_environ = os.getenv("CONFIG_PATH")
if config_path_environ:
config_path = config_path_environ
else:
2023-08-21 23:07:12 -06:00
config_path = Path(script_path, 'config', 'config.yml')
2023-08-21 21:28:52 -06:00
success, config, msg = load_config(config_path, script_path)
2023-08-21 21:28:52 -06:00
if not success:
print('Failed to load config:', msg)
sys.exit(1)
database.init_db(config['mysql']['host'], config['mysql']['username'], config['mysql']['password'], config['mysql']['database'])
create_db()
llm_server.llm.redis = RedisWrapper('local_llm')
create_db()
2023-09-17 18:55:36 -06:00
2023-08-21 22:49:44 -06:00
# print(app.url_map)
2023-08-21 21:28:52 -06:00
@app.route('/')
2023-08-23 23:11:12 -06:00
@app.route('/api')
@app.route('/api/openai')
2023-09-26 22:09:11 -06:00
@flask_cache.cached(timeout=10)
2023-08-23 23:11:12 -06:00
def home():
stats = generate_stats()
2023-08-23 23:11:12 -06:00
if not stats['online']:
2023-08-23 23:11:12 -06:00
running_model = estimated_wait_sec = 'offline'
else:
2023-09-26 13:32:33 -06:00
running_model = redis.get('running_model', str, 'ERROR')
2023-09-23 21:17:13 -06:00
active_gen_workers = get_active_gen_workers()
if stats['queue']['queued'] == 0 and active_gen_workers >= opts.concurrent_gens:
# There will be a wait if the queue is empty but prompts are processing, but we don't
# know how long.
estimated_wait_sec = f"less than {stats['stats']['average_generation_elapsed_sec']} seconds"
else:
2023-08-27 22:24:44 -06:00
estimated_wait_sec = f"{stats['queue']['estimated_wait_sec']} seconds"
2023-08-23 23:11:12 -06:00
if len(config['analytics_tracking_code']):
analytics_tracking_code = f"<script>\n{config['analytics_tracking_code']}\n</script>"
else:
analytics_tracking_code = ''
if config['info_html']:
2023-09-13 20:40:55 -06:00
info_html = config['info_html']
else:
info_html = ''
mode_info = ''
if opts.mode == 'vllm':
mode_info = vllm_info
base_client_api = redis.get('base_client_api', str)
2023-09-17 18:55:36 -06:00
2023-08-23 23:11:12 -06:00
return render_template('home.html',
2023-09-12 16:40:09 -06:00
llm_middleware_name=opts.llm_middleware_name,
analytics_tracking_code=analytics_tracking_code,
info_html=info_html,
current_model=opts.manual_model_name if opts.manual_model_name else running_model,
client_api=f'https://{base_client_api}',
ws_client_api=f'wss://{base_client_api}/v1/stream' if opts.enable_streaming else None,
2023-08-23 23:11:12 -06:00
estimated_wait=estimated_wait_sec,
mode_name=mode_ui_names[opts.mode][0],
api_input_textbox=mode_ui_names[opts.mode][1],
2023-08-29 17:56:12 -06:00
streaming_input_textbox=mode_ui_names[opts.mode][2],
2023-08-23 23:11:12 -06:00
context_size=opts.context_size,
2023-08-29 14:00:35 -06:00
stats_json=json.dumps(stats, indent=4, ensure_ascii=False),
extra_info=mode_info,
2023-09-17 18:55:36 -06:00
openai_client_api=f'https://{base_client_api}/openai/v1' if opts.enable_openi_compatible_backend else 'disabled',
expose_openai_system_prompt=opts.expose_openai_system_prompt,
enable_streaming=opts.enable_streaming,
2023-08-23 23:11:12 -06:00
)
# TODO: add authenticated route to get the current backend URL. Add it to /v1/backend
2023-08-21 21:28:52 -06:00
@app.route('/<first>')
@app.route('/<first>/<path:rest>')
def fallback(first=None, rest=None):
return jsonify({
2023-08-30 18:53:26 -06:00
'code': 404,
2023-08-21 21:28:52 -06:00
'msg': 'not found'
}), 404
@app.errorhandler(500)
def server_error(e):
return handle_server_error(e)
2023-09-17 18:55:36 -06:00
@app.before_request
def before_app_request():
2023-09-23 23:24:08 -06:00
auto_set_base_client_api(request)
2023-09-17 18:55:36 -06:00
2023-08-21 21:28:52 -06:00
if __name__ == "__main__":
server_startup(None)
2023-09-26 22:09:11 -06:00
print('FLASK MODE - Startup complete!')
app.run(host='0.0.0.0', threaded=False, processes=15)