This repository has been archived on 2024-10-27. You can view files and clone it, but cannot push or open issues or pull requests.
local-llm-server/llm_server/routes/openai/chat_completions.py

157 lines
7.1 KiB
Python
Raw Normal View History

import json
import time
2023-09-14 14:36:22 -06:00
import traceback
from flask import Response, jsonify, request
2023-09-12 16:40:09 -06:00
from llm_server.custom_redis import redis
2023-09-29 00:09:44 -06:00
from . import openai_bp
2023-09-12 16:40:09 -06:00
from ..helpers.http import validate_json
2023-09-26 22:09:11 -06:00
from ..openai_request_handler import OpenAIRequestHandler
2023-10-01 16:04:53 -06:00
from ..queue import decr_active_workers, decrement_ip_count, priority_queue
from ... import opts
from ...database.log_to_db import log_to_db
from ...llm.generator import generator
2023-10-01 16:04:53 -06:00
from ...llm.openai.oai_to_vllm import oai_to_vllm, validate_oai
2023-10-01 14:15:01 -06:00
from ...llm.openai.transform import generate_oai_string, transform_messages_to_prompt, trim_messages_to_fit
2023-09-12 16:40:09 -06:00
# TODO: add rate-limit headers?
2023-09-12 16:40:09 -06:00
@openai_bp.route('/chat/completions', methods=['POST'])
def openai_chat_completions():
request_valid_json, request_json_body = validate_json(request)
if not request_valid_json or not request_json_body.get('messages') or not request_json_body.get('model'):
2023-09-12 16:40:09 -06:00
return jsonify({'code': 400, 'msg': 'invalid JSON'}), 400
else:
2023-10-01 14:15:01 -06:00
handler = OpenAIRequestHandler(incoming_request=request, incoming_json=request_json_body)
if not request_json_body.get('stream'):
try:
2023-10-01 22:58:08 -06:00
invalid_oai_err_msg = validate_oai(request_json_body)
if invalid_oai_err_msg:
return invalid_oai_err_msg
2023-10-01 14:15:01 -06:00
return handler.handle_request()
except Exception:
traceback.print_exc()
return 'Internal server error', 500
else:
if not opts.enable_streaming:
return
handler.parameters, _ = handler.get_parameters()
handler.request_json_body = {
'messages': handler.request_json_body['messages'],
'model': handler.request_json_body['model'],
**handler.parameters
}
2023-10-01 16:04:53 -06:00
invalid_oai_err_msg = validate_oai(handler.request_json_body)
if invalid_oai_err_msg:
return invalid_oai_err_msg
handler.request_json_body = oai_to_vllm(handler.request_json_body, stop_hashes=True, mode=handler.cluster_backend_info['mode'])
2023-10-01 14:15:01 -06:00
if opts.openai_silent_trim:
2023-10-01 16:04:53 -06:00
handler.prompt = transform_messages_to_prompt(trim_messages_to_fit(handler.request.json['messages'], handler.cluster_backend_info['model_config']['max_position_embeddings'], handler.backend_url))
else:
handler.prompt = transform_messages_to_prompt(handler.request.json['messages'])
response_status_code = 0
start_time = time.time()
2023-10-01 16:04:53 -06:00
request_valid, invalid_response = handler.validate_request()
if not request_valid:
2023-10-01 14:15:01 -06:00
return invalid_response
else:
msg_to_backend = {
**handler.parameters,
'prompt': handler.prompt,
'stream': True,
}
2023-10-01 16:04:53 -06:00
# Add a dummy event to the queue and wait for it to reach a worker
event = priority_queue.put((None, handler.client_ip, handler.token, None, handler.backend_url), handler.token_priority, handler.selected_model)
2023-10-01 16:04:53 -06:00
if not event:
log_to_db(
2023-10-01 16:04:53 -06:00
handler.client_ip,
handler.token,
handler.prompt,
None,
None,
handler.parameters,
request.headers,
response_status_code,
request.url,
handler.backend_url,
)
return handler.handle_ratelimited()
# Wait for a worker to get our request and discard it.
_, _, _ = event.wait()
try:
r_headers = dict(request.headers)
r_url = request.url
2023-09-29 00:09:44 -06:00
model = redis.get('running_model', 'ERROR', dtype=str) if opts.openai_expose_our_model else request_json_body.get('model')
2023-09-25 22:01:57 -06:00
oai_string = generate_oai_string(30)
def generate():
2023-10-05 18:36:02 -06:00
response = generator(msg_to_backend, handler.backend_url)
generated_text = ''
partial_response = b''
for chunk in response.iter_content(chunk_size=1):
partial_response += chunk
if partial_response.endswith(b'\x00'):
json_strs = partial_response.split(b'\x00')
for json_str in json_strs:
if json_str:
try:
json_obj = json.loads(json_str.decode())
new = json_obj['text'][0].split(handler.prompt + generated_text)[1]
generated_text = generated_text + new
except IndexError:
# ????
continue
data = {
"id": f"chatcmpl-{oai_string}",
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"delta": {
"content": new
},
"finish_reason": None
}
]
}
yield f'data: {json.dumps(data)}\n\n'
yield 'data: [DONE]\n\n'
end_time = time.time()
elapsed_time = end_time - start_time
log_to_db(
handler.client_ip,
handler.token,
handler.prompt,
generated_text,
elapsed_time,
handler.parameters,
r_headers,
response_status_code,
r_url,
handler.backend_url,
)
return Response(generate(), mimetype='text/event-stream')
2023-10-01 16:04:53 -06:00
except Exception:
traceback.print_exc()
return 'INTERNAL SERVER', 500
2023-10-05 18:36:02 -06:00
finally:
# The worker incremented it, we'll decrement it.
decrement_ip_count(handler.client_ip, 'processing_ips')
decr_active_workers(handler.selected_model, handler.backend_url)