2024-03-25 23:59:47 +09:00
|
|
|
import time
|
2024-07-16 12:18:09 +00:00
|
|
|
from typing import (AsyncGenerator, AsyncIterator, Awaitable, Dict, List,
|
|
|
|
Optional)
|
2024-05-30 11:52:14 +02:00
|
|
|
from typing import Sequence as GenericSequence
|
2024-07-16 12:18:09 +00:00
|
|
|
from typing import Union
|
2024-03-25 23:59:47 +09:00
|
|
|
|
2024-01-17 05:33:14 +00:00
|
|
|
from fastapi import Request
|
2024-07-18 00:13:30 -07:00
|
|
|
from transformers import PreTrainedTokenizer
|
2024-03-25 23:59:47 +09:00
|
|
|
|
2024-07-03 11:34:00 +08:00
|
|
|
from vllm.config import ModelConfig
|
2024-01-17 05:33:14 +00:00
|
|
|
from vllm.engine.async_llm_engine import AsyncLLMEngine
|
2024-07-21 08:38:17 +08:00
|
|
|
from vllm.entrypoints.chat_utils import (ConversationMessage,
|
|
|
|
load_chat_template,
|
|
|
|
parse_chat_message_content)
|
2024-07-23 01:13:53 +08:00
|
|
|
from vllm.entrypoints.logger import RequestLogger
|
2024-01-17 05:33:14 +00:00
|
|
|
from vllm.entrypoints.openai.protocol import (
|
2024-07-16 12:18:09 +00:00
|
|
|
ChatCompletionLogProb, ChatCompletionLogProbs,
|
|
|
|
ChatCompletionLogProbsContent, ChatCompletionNamedToolChoiceParam,
|
2024-06-04 01:25:29 +02:00
|
|
|
ChatCompletionRequest, ChatCompletionResponse,
|
2024-01-17 05:33:14 +00:00
|
|
|
ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice,
|
|
|
|
ChatCompletionStreamResponse, ChatMessage, DeltaMessage, ErrorResponse,
|
2024-06-04 01:25:29 +02:00
|
|
|
FunctionCall, ToolCall, UsageInfo)
|
2024-04-27 13:08:24 +08:00
|
|
|
from vllm.entrypoints.openai.serving_engine import (LoRAModulePath,
|
2024-07-23 01:13:53 +08:00
|
|
|
OpenAIServing,
|
|
|
|
PromptAdapterPath)
|
2024-06-07 11:23:32 -07:00
|
|
|
from vllm.inputs import PromptInputs
|
2024-03-25 23:59:47 +09:00
|
|
|
from vllm.logger import init_logger
|
2024-03-10 19:49:14 -07:00
|
|
|
from vllm.model_executor.guided_decoding import (
|
|
|
|
get_guided_decoding_logits_processor)
|
2024-07-02 00:57:09 -07:00
|
|
|
from vllm.multimodal import MultiModalDataDict
|
2024-03-25 23:59:47 +09:00
|
|
|
from vllm.outputs import RequestOutput
|
2024-05-30 11:52:14 +02:00
|
|
|
from vllm.sequence import Logprob
|
2024-06-18 19:17:03 +03:00
|
|
|
from vllm.tracing import (contains_trace_headers, extract_trace_headers,
|
|
|
|
log_tracing_disabled_warning)
|
2024-03-25 23:59:47 +09:00
|
|
|
from vllm.utils import random_uuid
|
2024-01-17 05:33:14 +00:00
|
|
|
|
|
|
|
logger = init_logger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class OpenAIServingChat(OpenAIServing):
|
|
|
|
|
2024-07-23 01:13:53 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
engine: AsyncLLMEngine,
|
|
|
|
model_config: ModelConfig,
|
|
|
|
served_model_names: List[str],
|
|
|
|
response_role: str,
|
|
|
|
*,
|
|
|
|
lora_modules: Optional[List[LoRAModulePath]],
|
|
|
|
prompt_adapters: Optional[List[PromptAdapterPath]],
|
|
|
|
request_logger: Optional[RequestLogger],
|
|
|
|
chat_template: Optional[str],
|
|
|
|
):
|
2024-02-17 15:00:48 -05:00
|
|
|
super().__init__(engine=engine,
|
2024-05-09 13:48:33 +08:00
|
|
|
model_config=model_config,
|
2024-04-18 08:16:26 +01:00
|
|
|
served_model_names=served_model_names,
|
2024-07-23 01:13:53 +08:00
|
|
|
lora_modules=lora_modules,
|
|
|
|
prompt_adapters=prompt_adapters,
|
|
|
|
request_logger=request_logger)
|
2024-05-03 20:04:14 +02:00
|
|
|
|
2024-01-17 05:33:14 +00:00
|
|
|
self.response_role = response_role
|
2024-07-18 00:13:30 -07:00
|
|
|
|
|
|
|
# If this is None we use the tokenizer's default chat template
|
|
|
|
self.chat_template = load_chat_template(chat_template)
|
2024-04-27 13:08:24 +08:00
|
|
|
|
2024-01-17 05:33:14 +00:00
|
|
|
async def create_chat_completion(
|
2024-05-15 19:13:36 -04:00
|
|
|
self,
|
|
|
|
request: ChatCompletionRequest,
|
|
|
|
raw_request: Optional[Request] = None
|
2024-01-17 05:33:14 +00:00
|
|
|
) -> Union[ErrorResponse, AsyncGenerator[str, None],
|
|
|
|
ChatCompletionResponse]:
|
|
|
|
"""Completion API similar to OpenAI's API.
|
|
|
|
|
2024-03-10 19:49:14 -07:00
|
|
|
See https://platform.openai.com/docs/api-reference/chat/create
|
|
|
|
for the API specification. This API mimics the OpenAI
|
|
|
|
ChatCompletion API.
|
2024-01-17 05:33:14 +00:00
|
|
|
|
2024-02-26 19:51:53 -08:00
|
|
|
NOTE: Currently we do not support the following feature:
|
2024-01-17 05:33:14 +00:00
|
|
|
- function_call (Users should implement this by themselves)
|
|
|
|
"""
|
|
|
|
error_check_ret = await self._check_model(request)
|
|
|
|
if error_check_ret is not None:
|
|
|
|
return error_check_ret
|
|
|
|
|
|
|
|
try:
|
2024-07-23 01:13:53 +08:00
|
|
|
(
|
|
|
|
lora_request,
|
|
|
|
prompt_adapter_request,
|
|
|
|
) = self._maybe_get_adapters(request)
|
|
|
|
|
|
|
|
model_config = self.model_config
|
2024-07-18 00:13:30 -07:00
|
|
|
tokenizer = await self.engine.get_tokenizer(lora_request)
|
|
|
|
|
2024-04-27 13:08:24 +08:00
|
|
|
conversation: List[ConversationMessage] = []
|
2024-07-02 00:57:09 -07:00
|
|
|
mm_futures: List[Awaitable[MultiModalDataDict]] = []
|
2024-04-27 13:08:24 +08:00
|
|
|
|
2024-05-16 05:58:46 +08:00
|
|
|
for msg in request.messages:
|
2024-07-18 00:13:30 -07:00
|
|
|
chat_parsed_result = parse_chat_message_content(
|
2024-07-23 01:13:53 +08:00
|
|
|
msg, model_config, tokenizer)
|
2024-04-27 13:08:24 +08:00
|
|
|
|
2024-06-07 11:23:32 -07:00
|
|
|
conversation.extend(chat_parsed_result.messages)
|
2024-07-02 00:57:09 -07:00
|
|
|
mm_futures.extend(chat_parsed_result.mm_futures)
|
2024-04-27 13:08:24 +08:00
|
|
|
|
2024-07-02 09:01:57 +03:00
|
|
|
tool_dicts = None if request.tools is None else [
|
|
|
|
tool.model_dump() for tool in request.tools
|
|
|
|
]
|
|
|
|
|
2024-07-18 00:13:30 -07:00
|
|
|
prompt = tokenizer.apply_chat_template(
|
2024-04-27 13:08:24 +08:00
|
|
|
conversation=conversation,
|
2024-01-17 05:33:14 +00:00
|
|
|
tokenize=False,
|
2024-04-27 13:08:24 +08:00
|
|
|
add_generation_prompt=request.add_generation_prompt,
|
2024-07-02 09:01:57 +03:00
|
|
|
tools=tool_dicts,
|
|
|
|
documents=request.documents,
|
2024-07-18 00:13:30 -07:00
|
|
|
chat_template=request.chat_template or self.chat_template,
|
2024-07-02 09:01:57 +03:00
|
|
|
**(request.chat_template_kwargs or {}),
|
2024-04-27 13:08:24 +08:00
|
|
|
)
|
2024-01-17 05:33:14 +00:00
|
|
|
except Exception as e:
|
2024-04-26 16:16:58 +09:00
|
|
|
logger.error("Error in applying chat template from request: %s", e)
|
2024-01-17 05:33:14 +00:00
|
|
|
return self.create_error_response(str(e))
|
|
|
|
|
2024-07-02 00:57:09 -07:00
|
|
|
mm_data: Optional[MultiModalDataDict] = None
|
2024-06-07 11:23:32 -07:00
|
|
|
try:
|
2024-07-02 00:57:09 -07:00
|
|
|
if len(mm_futures):
|
|
|
|
# since we support only single mm data currently
|
2024-07-02 23:41:23 -07:00
|
|
|
assert len(
|
|
|
|
mm_futures
|
|
|
|
) == 1, "Multiple 'image_url' input is currently not supported."
|
2024-07-02 00:57:09 -07:00
|
|
|
mm_data = await mm_futures[0]
|
2024-06-07 11:23:32 -07:00
|
|
|
except Exception as e:
|
2024-07-02 00:57:09 -07:00
|
|
|
logger.error("Error in loading multi-modal data: %s", e)
|
2024-06-07 11:23:32 -07:00
|
|
|
return self.create_error_response(str(e))
|
|
|
|
|
2024-07-23 01:13:53 +08:00
|
|
|
request_id = f"chat-{random_uuid()}"
|
2024-01-17 05:33:14 +00:00
|
|
|
try:
|
2024-01-18 16:45:14 -08:00
|
|
|
sampling_params = request.to_sampling_params()
|
2024-04-27 19:30:08 +08:00
|
|
|
decoding_config = await self.engine.get_decoding_config()
|
2024-04-16 08:54:57 +03:00
|
|
|
guided_decoding_backend = request.guided_decoding_backend \
|
|
|
|
or decoding_config.guided_decoding_backend
|
2024-02-29 14:13:08 -08:00
|
|
|
guided_decode_logits_processor = (
|
2024-07-18 00:13:30 -07:00
|
|
|
await
|
|
|
|
get_guided_decoding_logits_processor(guided_decoding_backend,
|
|
|
|
request, tokenizer))
|
2024-02-29 14:13:08 -08:00
|
|
|
if guided_decode_logits_processor:
|
|
|
|
if sampling_params.logits_processors is None:
|
|
|
|
sampling_params.logits_processors = []
|
|
|
|
sampling_params.logits_processors.append(
|
|
|
|
guided_decode_logits_processor)
|
2024-07-23 01:13:53 +08:00
|
|
|
|
|
|
|
prompt_inputs = self._tokenize_prompt_input(
|
|
|
|
request,
|
|
|
|
tokenizer,
|
|
|
|
prompt,
|
|
|
|
truncate_prompt_tokens=sampling_params.truncate_prompt_tokens,
|
|
|
|
add_special_tokens=request.add_special_tokens,
|
|
|
|
)
|
|
|
|
|
|
|
|
self._log_inputs(request_id,
|
|
|
|
prompt_inputs,
|
|
|
|
params=sampling_params,
|
|
|
|
lora_request=lora_request,
|
|
|
|
prompt_adapter_request=prompt_adapter_request)
|
|
|
|
|
|
|
|
engine_inputs: PromptInputs = {
|
|
|
|
"prompt_token_ids": prompt_inputs["prompt_token_ids"],
|
|
|
|
}
|
|
|
|
if mm_data is not None:
|
|
|
|
engine_inputs["multi_modal_data"] = mm_data
|
|
|
|
|
|
|
|
is_tracing_enabled = await self.engine.is_tracing_enabled()
|
|
|
|
trace_headers = None
|
|
|
|
if is_tracing_enabled and raw_request:
|
|
|
|
trace_headers = extract_trace_headers(raw_request.headers)
|
|
|
|
if (not is_tracing_enabled and raw_request
|
|
|
|
and contains_trace_headers(raw_request.headers)):
|
|
|
|
log_tracing_disabled_warning()
|
|
|
|
|
|
|
|
result_generator = self.engine.generate(
|
|
|
|
engine_inputs,
|
|
|
|
sampling_params,
|
|
|
|
request_id,
|
|
|
|
lora_request=lora_request,
|
|
|
|
trace_headers=trace_headers,
|
|
|
|
prompt_adapter_request=prompt_adapter_request,
|
|
|
|
)
|
2024-01-17 05:33:14 +00:00
|
|
|
except ValueError as e:
|
2024-07-23 01:13:53 +08:00
|
|
|
# TODO: Use a vllm-specific Validation Error
|
2024-01-17 05:33:14 +00:00
|
|
|
return self.create_error_response(str(e))
|
|
|
|
|
|
|
|
# Streaming response
|
|
|
|
if request.stream:
|
|
|
|
return self.chat_completion_stream_generator(
|
2024-07-18 00:13:30 -07:00
|
|
|
request, result_generator, request_id, conversation, tokenizer)
|
2024-01-17 05:33:14 +00:00
|
|
|
else:
|
2024-03-04 11:54:06 -08:00
|
|
|
try:
|
|
|
|
return await self.chat_completion_full_generator(
|
2024-05-01 01:28:46 +02:00
|
|
|
request, raw_request, result_generator, request_id,
|
2024-07-18 00:13:30 -07:00
|
|
|
conversation, tokenizer)
|
2024-03-04 11:54:06 -08:00
|
|
|
except ValueError as e:
|
|
|
|
# TODO: Use a vllm-specific Validation Error
|
|
|
|
return self.create_error_response(str(e))
|
2024-01-17 05:33:14 +00:00
|
|
|
|
|
|
|
def get_chat_request_role(self, request: ChatCompletionRequest) -> str:
|
|
|
|
if request.add_generation_prompt:
|
|
|
|
return self.response_role
|
|
|
|
else:
|
2024-02-29 01:04:07 -05:00
|
|
|
return request.messages[-1]["role"]
|
2024-01-17 05:33:14 +00:00
|
|
|
|
|
|
|
async def chat_completion_stream_generator(
|
2024-07-18 00:13:30 -07:00
|
|
|
self,
|
|
|
|
request: ChatCompletionRequest,
|
|
|
|
result_generator: AsyncIterator[RequestOutput],
|
|
|
|
request_id: str,
|
|
|
|
conversation: List[ConversationMessage],
|
|
|
|
tokenizer: PreTrainedTokenizer,
|
2024-05-01 01:28:46 +02:00
|
|
|
) -> AsyncGenerator[str, None]:
|
2024-04-18 08:16:26 +01:00
|
|
|
model_name = self.served_model_names[0]
|
2024-03-16 02:25:43 +08:00
|
|
|
created_time = int(time.time())
|
2024-01-17 05:33:14 +00:00
|
|
|
chunk_object_type = "chat.completion.chunk"
|
2024-03-04 11:54:06 -08:00
|
|
|
first_iteration = True
|
2024-01-17 05:33:14 +00:00
|
|
|
|
|
|
|
# Send response for each token for each request.n (index)
|
2024-07-23 01:13:53 +08:00
|
|
|
num_choices = 1 if request.n is None else request.n
|
|
|
|
previous_texts = [""] * num_choices
|
|
|
|
previous_num_tokens = [0] * num_choices
|
|
|
|
finish_reason_sent = [False] * num_choices
|
|
|
|
|
2024-03-04 11:54:06 -08:00
|
|
|
try:
|
|
|
|
async for res in result_generator:
|
|
|
|
# We need to do it here, because if there are exceptions in
|
|
|
|
# the result_generator, it needs to be sent as the FIRST
|
|
|
|
# response (by the try...catch).
|
|
|
|
if first_iteration:
|
2024-03-10 19:49:14 -07:00
|
|
|
# Send first response for each request.n (index) with
|
|
|
|
# the role
|
2024-03-04 11:54:06 -08:00
|
|
|
role = self.get_chat_request_role(request)
|
2024-07-23 01:13:53 +08:00
|
|
|
for i in range(num_choices):
|
2024-03-04 11:54:06 -08:00
|
|
|
choice_data = ChatCompletionResponseStreamChoice(
|
|
|
|
index=i,
|
|
|
|
delta=DeltaMessage(role=role),
|
|
|
|
logprobs=None,
|
|
|
|
finish_reason=None)
|
|
|
|
chunk = ChatCompletionStreamResponse(
|
|
|
|
id=request_id,
|
|
|
|
object=chunk_object_type,
|
|
|
|
created=created_time,
|
|
|
|
choices=[choice_data],
|
|
|
|
model=model_name)
|
2024-06-07 06:29:24 +03:00
|
|
|
if (request.stream_options
|
|
|
|
and request.stream_options.include_usage):
|
2024-07-23 21:41:55 +03:00
|
|
|
if (request.stream_options.continuous_usage_stats):
|
|
|
|
prompt_tokens = len(res.prompt_token_ids)
|
|
|
|
usage = UsageInfo(prompt_tokens=prompt_tokens,
|
|
|
|
completion_tokens=0,
|
|
|
|
total_tokens=prompt_tokens)
|
|
|
|
chunk.usage = usage
|
|
|
|
else:
|
|
|
|
chunk.usage = None
|
|
|
|
|
2024-03-04 11:54:06 -08:00
|
|
|
data = chunk.model_dump_json(exclude_unset=True)
|
|
|
|
yield f"data: {data}\n\n"
|
|
|
|
|
2024-03-10 19:49:14 -07:00
|
|
|
# Send response to echo the input portion of the
|
|
|
|
# last message
|
2024-03-04 11:54:06 -08:00
|
|
|
if request.echo:
|
|
|
|
last_msg_content = ""
|
2024-05-01 01:28:46 +02:00
|
|
|
if conversation and conversation[-1].get(
|
|
|
|
"content") and conversation[-1].get(
|
|
|
|
"role") == role:
|
|
|
|
last_msg_content = conversation[-1]["content"]
|
2024-03-04 11:54:06 -08:00
|
|
|
|
|
|
|
if last_msg_content:
|
2024-07-23 01:13:53 +08:00
|
|
|
for i in range(num_choices):
|
2024-03-10 19:49:14 -07:00
|
|
|
choice_data = (
|
|
|
|
ChatCompletionResponseStreamChoice(
|
|
|
|
index=i,
|
|
|
|
delta=DeltaMessage(
|
|
|
|
content=last_msg_content),
|
2024-07-23 01:13:53 +08:00
|
|
|
logprobs=None,
|
2024-03-10 19:49:14 -07:00
|
|
|
finish_reason=None))
|
2024-03-04 11:54:06 -08:00
|
|
|
chunk = ChatCompletionStreamResponse(
|
|
|
|
id=request_id,
|
|
|
|
object=chunk_object_type,
|
|
|
|
created=created_time,
|
|
|
|
choices=[choice_data],
|
|
|
|
model=model_name)
|
2024-06-07 06:29:24 +03:00
|
|
|
if (request.stream_options and
|
|
|
|
request.stream_options.include_usage):
|
2024-07-23 21:41:55 +03:00
|
|
|
if (request.stream_options.
|
|
|
|
continuous_usage_stats):
|
|
|
|
prompt_tokens = len(
|
|
|
|
res.prompt_token_ids)
|
|
|
|
usage = UsageInfo(
|
|
|
|
prompt_tokens=prompt_tokens,
|
|
|
|
completion_tokens=0,
|
|
|
|
total_tokens=prompt_tokens)
|
|
|
|
chunk.usage = usage
|
|
|
|
else:
|
|
|
|
chunk.usage = None
|
|
|
|
|
2024-03-04 11:54:06 -08:00
|
|
|
data = chunk.model_dump_json(
|
|
|
|
exclude_unset=True)
|
|
|
|
yield f"data: {data}\n\n"
|
|
|
|
first_iteration = False
|
|
|
|
|
|
|
|
for output in res.outputs:
|
|
|
|
i = output.index
|
|
|
|
|
|
|
|
if finish_reason_sent[i]:
|
|
|
|
continue
|
|
|
|
|
|
|
|
delta_token_ids = output.token_ids[previous_num_tokens[i]:]
|
2024-06-11 13:36:46 +08:00
|
|
|
out_logprobs = output.logprobs[
|
2024-03-04 11:54:06 -08:00
|
|
|
previous_num_tokens[i]:] if output.logprobs else None
|
|
|
|
|
2024-06-11 13:36:46 +08:00
|
|
|
if request.logprobs and request.top_logprobs is not None:
|
|
|
|
assert out_logprobs is not None, (
|
|
|
|
"Did not output logprobs")
|
2024-05-30 11:52:14 +02:00
|
|
|
logprobs = self._create_chat_logprobs(
|
2024-03-04 11:54:06 -08:00
|
|
|
token_ids=delta_token_ids,
|
2024-06-11 13:36:46 +08:00
|
|
|
top_logprobs=out_logprobs,
|
2024-07-18 00:13:30 -07:00
|
|
|
tokenizer=tokenizer,
|
2024-05-30 02:13:22 +03:00
|
|
|
num_output_top_logprobs=request.top_logprobs,
|
2024-03-04 11:54:06 -08:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
logprobs = None
|
|
|
|
|
|
|
|
delta_text = output.text[len(previous_texts[i]):]
|
|
|
|
previous_texts[i] = output.text
|
|
|
|
previous_num_tokens[i] = len(output.token_ids)
|
2024-06-04 01:25:29 +02:00
|
|
|
|
|
|
|
if request.tool_choice and type(
|
|
|
|
request.tool_choice
|
|
|
|
) is ChatCompletionNamedToolChoiceParam:
|
|
|
|
delta_message = DeltaMessage(tool_calls=[
|
|
|
|
ToolCall(function=FunctionCall(
|
|
|
|
name=request.tool_choice.function.name,
|
|
|
|
arguments=delta_text))
|
|
|
|
])
|
|
|
|
else:
|
|
|
|
delta_message = DeltaMessage(content=delta_text)
|
|
|
|
|
2024-03-04 11:54:06 -08:00
|
|
|
if output.finish_reason is None:
|
|
|
|
# Send token-by-token response for each request.n
|
2024-06-04 01:25:29 +02:00
|
|
|
|
2024-03-04 11:54:06 -08:00
|
|
|
choice_data = ChatCompletionResponseStreamChoice(
|
|
|
|
index=i,
|
2024-06-04 01:25:29 +02:00
|
|
|
delta=delta_message,
|
2024-03-04 11:54:06 -08:00
|
|
|
logprobs=logprobs,
|
|
|
|
finish_reason=None)
|
|
|
|
chunk = ChatCompletionStreamResponse(
|
|
|
|
id=request_id,
|
|
|
|
object=chunk_object_type,
|
|
|
|
created=created_time,
|
|
|
|
choices=[choice_data],
|
|
|
|
model=model_name)
|
2024-06-07 06:29:24 +03:00
|
|
|
if (request.stream_options
|
|
|
|
and request.stream_options.include_usage):
|
2024-07-23 21:41:55 +03:00
|
|
|
if (request.stream_options.continuous_usage_stats):
|
|
|
|
prompt_tokens = len(res.prompt_token_ids)
|
|
|
|
completion_tokens = len(output.token_ids)
|
|
|
|
usage = UsageInfo(
|
|
|
|
prompt_tokens=prompt_tokens,
|
|
|
|
completion_tokens=completion_tokens,
|
|
|
|
total_tokens=prompt_tokens +
|
|
|
|
completion_tokens,
|
|
|
|
)
|
|
|
|
chunk.usage = usage
|
|
|
|
else:
|
|
|
|
chunk.usage = None
|
|
|
|
|
2024-03-04 11:54:06 -08:00
|
|
|
data = chunk.model_dump_json(exclude_unset=True)
|
|
|
|
yield f"data: {data}\n\n"
|
|
|
|
else:
|
|
|
|
# Send the finish response for each request.n only once
|
|
|
|
prompt_tokens = len(res.prompt_token_ids)
|
|
|
|
choice_data = ChatCompletionResponseStreamChoice(
|
|
|
|
index=i,
|
2024-06-04 01:25:29 +02:00
|
|
|
delta=delta_message,
|
2024-03-04 11:54:06 -08:00
|
|
|
logprobs=logprobs,
|
2024-03-25 17:31:32 -07:00
|
|
|
finish_reason=output.finish_reason,
|
|
|
|
stop_reason=output.stop_reason)
|
2024-03-04 11:54:06 -08:00
|
|
|
chunk = ChatCompletionStreamResponse(
|
|
|
|
id=request_id,
|
|
|
|
object=chunk_object_type,
|
|
|
|
created=created_time,
|
|
|
|
choices=[choice_data],
|
|
|
|
model=model_name)
|
2024-06-07 06:29:24 +03:00
|
|
|
if (request.stream_options
|
|
|
|
and request.stream_options.include_usage):
|
2024-07-23 21:41:55 +03:00
|
|
|
if (request.stream_options.continuous_usage_stats):
|
|
|
|
prompt_tokens = len(res.prompt_token_ids)
|
|
|
|
completion_tokens = len(output.token_ids)
|
|
|
|
usage = UsageInfo(
|
|
|
|
prompt_tokens=prompt_tokens,
|
|
|
|
completion_tokens=completion_tokens,
|
|
|
|
total_tokens=prompt_tokens +
|
|
|
|
completion_tokens,
|
|
|
|
)
|
|
|
|
chunk.usage = usage
|
|
|
|
else:
|
|
|
|
chunk.usage = None
|
2024-06-07 06:29:24 +03:00
|
|
|
data = chunk.model_dump_json(exclude_unset=True)
|
2024-03-04 11:54:06 -08:00
|
|
|
yield f"data: {data}\n\n"
|
|
|
|
finish_reason_sent[i] = True
|
2024-06-07 06:29:24 +03:00
|
|
|
|
2024-06-10 17:22:09 +03:00
|
|
|
if (request.stream_options
|
|
|
|
and request.stream_options.include_usage):
|
|
|
|
final_usage = UsageInfo(
|
|
|
|
prompt_tokens=prompt_tokens,
|
|
|
|
completion_tokens=previous_num_tokens[i],
|
|
|
|
total_tokens=prompt_tokens + previous_num_tokens[i],
|
|
|
|
)
|
|
|
|
|
|
|
|
final_usage_chunk = ChatCompletionStreamResponse(
|
|
|
|
id=request_id,
|
|
|
|
object=chunk_object_type,
|
|
|
|
created=created_time,
|
|
|
|
choices=[],
|
|
|
|
model=model_name,
|
|
|
|
usage=final_usage)
|
|
|
|
final_usage_data = (final_usage_chunk.model_dump_json(
|
|
|
|
exclude_unset=True, exclude_none=True))
|
|
|
|
yield f"data: {final_usage_data}\n\n"
|
2024-06-07 06:29:24 +03:00
|
|
|
|
2024-03-04 11:54:06 -08:00
|
|
|
except ValueError as e:
|
|
|
|
# TODO: Use a vllm-specific Validation Error
|
|
|
|
data = self.create_streaming_error_response(str(e))
|
|
|
|
yield f"data: {data}\n\n"
|
2024-01-17 05:33:14 +00:00
|
|
|
# Send the final done message after all response.n are finished
|
|
|
|
yield "data: [DONE]\n\n"
|
|
|
|
|
|
|
|
async def chat_completion_full_generator(
|
2024-07-18 00:13:30 -07:00
|
|
|
self,
|
|
|
|
request: ChatCompletionRequest,
|
|
|
|
raw_request: Optional[Request],
|
|
|
|
result_generator: AsyncIterator[RequestOutput],
|
|
|
|
request_id: str,
|
|
|
|
conversation: List[ConversationMessage],
|
|
|
|
tokenizer: PreTrainedTokenizer,
|
2024-05-01 01:28:46 +02:00
|
|
|
) -> Union[ErrorResponse, ChatCompletionResponse]:
|
2024-01-17 05:33:14 +00:00
|
|
|
|
2024-04-18 08:16:26 +01:00
|
|
|
model_name = self.served_model_names[0]
|
2024-03-16 02:25:43 +08:00
|
|
|
created_time = int(time.time())
|
2024-04-27 13:08:24 +08:00
|
|
|
final_res: Optional[RequestOutput] = None
|
2024-01-17 05:33:14 +00:00
|
|
|
|
|
|
|
async for res in result_generator:
|
2024-05-15 19:13:36 -04:00
|
|
|
if raw_request is not None and await raw_request.is_disconnected():
|
2024-01-17 05:33:14 +00:00
|
|
|
# Abort the request if the client disconnects.
|
|
|
|
await self.engine.abort(request_id)
|
|
|
|
return self.create_error_response("Client disconnected")
|
|
|
|
final_res = res
|
|
|
|
assert final_res is not None
|
|
|
|
|
2024-06-15 12:45:31 +08:00
|
|
|
choices: List[ChatCompletionResponseChoice] = []
|
2024-02-25 18:39:34 -08:00
|
|
|
|
2024-01-17 05:33:14 +00:00
|
|
|
role = self.get_chat_request_role(request)
|
|
|
|
for output in final_res.outputs:
|
2024-02-25 18:39:34 -08:00
|
|
|
token_ids = output.token_ids
|
2024-06-11 13:36:46 +08:00
|
|
|
out_logprobs = output.logprobs
|
2024-02-25 18:39:34 -08:00
|
|
|
|
2024-06-11 13:36:46 +08:00
|
|
|
if request.logprobs and request.top_logprobs is not None:
|
|
|
|
assert out_logprobs is not None, "Did not output logprobs"
|
2024-05-30 11:52:14 +02:00
|
|
|
logprobs = self._create_chat_logprobs(
|
2024-02-25 18:39:34 -08:00
|
|
|
token_ids=token_ids,
|
2024-06-11 13:36:46 +08:00
|
|
|
top_logprobs=out_logprobs,
|
2024-05-30 02:13:22 +03:00
|
|
|
num_output_top_logprobs=request.top_logprobs,
|
2024-07-18 00:13:30 -07:00
|
|
|
tokenizer=tokenizer,
|
2024-02-25 18:39:34 -08:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
logprobs = None
|
|
|
|
|
2024-06-04 01:25:29 +02:00
|
|
|
if request.tool_choice and type(
|
|
|
|
request.tool_choice) is ChatCompletionNamedToolChoiceParam:
|
|
|
|
message = ChatMessage(
|
|
|
|
role=role,
|
|
|
|
content="",
|
|
|
|
tool_calls=[
|
|
|
|
ToolCall(function=FunctionCall(
|
|
|
|
name=request.tool_choice.function.name,
|
|
|
|
arguments=output.text))
|
|
|
|
])
|
|
|
|
elif not request.tool_choice or request.tool_choice == "none":
|
|
|
|
message = ChatMessage(role=role, content=output.text)
|
|
|
|
|
2024-01-17 05:33:14 +00:00
|
|
|
choice_data = ChatCompletionResponseChoice(
|
|
|
|
index=output.index,
|
2024-06-04 01:25:29 +02:00
|
|
|
message=message,
|
2024-02-25 18:39:34 -08:00
|
|
|
logprobs=logprobs,
|
2024-01-17 05:33:14 +00:00
|
|
|
finish_reason=output.finish_reason,
|
2024-05-30 11:52:14 +02:00
|
|
|
stop_reason=output.stop_reason)
|
2024-01-17 05:33:14 +00:00
|
|
|
choices.append(choice_data)
|
|
|
|
|
|
|
|
if request.echo:
|
|
|
|
last_msg_content = ""
|
2024-05-01 01:28:46 +02:00
|
|
|
if conversation and conversation[-1].get(
|
|
|
|
"content") and conversation[-1].get("role") == role:
|
|
|
|
last_msg_content = conversation[-1]["content"]
|
2024-01-17 05:33:14 +00:00
|
|
|
|
|
|
|
for choice in choices:
|
|
|
|
full_message = last_msg_content + choice.message.content
|
|
|
|
choice.message.content = full_message
|
|
|
|
|
|
|
|
num_prompt_tokens = len(final_res.prompt_token_ids)
|
|
|
|
num_generated_tokens = sum(
|
|
|
|
len(output.token_ids) for output in final_res.outputs)
|
|
|
|
usage = UsageInfo(
|
|
|
|
prompt_tokens=num_prompt_tokens,
|
|
|
|
completion_tokens=num_generated_tokens,
|
|
|
|
total_tokens=num_prompt_tokens + num_generated_tokens,
|
|
|
|
)
|
|
|
|
response = ChatCompletionResponse(
|
|
|
|
id=request_id,
|
|
|
|
created=created_time,
|
|
|
|
model=model_name,
|
|
|
|
choices=choices,
|
|
|
|
usage=usage,
|
|
|
|
)
|
|
|
|
|
2024-05-16 05:58:46 +08:00
|
|
|
return response
|
2024-05-30 11:52:14 +02:00
|
|
|
|
|
|
|
def _get_top_logprobs(
|
2024-07-18 00:13:30 -07:00
|
|
|
self, logprobs: Dict[int, Logprob], top_logprobs: Optional[int],
|
|
|
|
tokenizer: PreTrainedTokenizer) -> List[ChatCompletionLogProb]:
|
2024-05-30 11:52:14 +02:00
|
|
|
return [
|
|
|
|
ChatCompletionLogProb(
|
2024-07-18 00:13:30 -07:00
|
|
|
token=(token := self._get_decoded_token(p[1], p[0],
|
|
|
|
tokenizer)),
|
2024-05-30 11:52:14 +02:00
|
|
|
logprob=max(p[1].logprob, -9999.0),
|
2024-07-18 00:13:30 -07:00
|
|
|
bytes=list(token.encode("utf-8", errors="replace")))
|
2024-05-30 11:52:14 +02:00
|
|
|
for i, p in enumerate(logprobs.items())
|
|
|
|
if top_logprobs and i < top_logprobs
|
|
|
|
]
|
|
|
|
|
|
|
|
def _create_chat_logprobs(
|
|
|
|
self,
|
|
|
|
token_ids: GenericSequence[int],
|
|
|
|
top_logprobs: GenericSequence[Optional[Dict[int, Logprob]]],
|
2024-07-18 00:13:30 -07:00
|
|
|
tokenizer: PreTrainedTokenizer,
|
2024-05-30 11:52:14 +02:00
|
|
|
num_output_top_logprobs: Optional[int] = None,
|
|
|
|
) -> ChatCompletionLogProbs:
|
|
|
|
"""Create OpenAI-style logprobs."""
|
|
|
|
|
|
|
|
logprobs_content = []
|
|
|
|
|
|
|
|
for i, token_id in enumerate(token_ids):
|
|
|
|
step_top_logprobs = top_logprobs[i]
|
|
|
|
if step_top_logprobs is None:
|
2024-07-18 00:13:30 -07:00
|
|
|
token = tokenizer.decode(token_id)
|
2024-05-30 11:52:14 +02:00
|
|
|
logprobs_content.append(
|
|
|
|
ChatCompletionLogProbsContent(
|
2024-07-18 00:13:30 -07:00
|
|
|
token=token,
|
|
|
|
bytes=list(token.encode("utf-8", errors="replace"))))
|
2024-05-30 11:52:14 +02:00
|
|
|
else:
|
|
|
|
logprobs_content.append(
|
|
|
|
ChatCompletionLogProbsContent(
|
|
|
|
token=step_top_logprobs[token_id].decoded_token,
|
|
|
|
logprob=max(step_top_logprobs[token_id].logprob,
|
|
|
|
-9999.0),
|
|
|
|
bytes=list(
|
|
|
|
step_top_logprobs[token_id].decoded_token.encode(
|
|
|
|
"utf-8", errors="replace")),
|
|
|
|
top_logprobs=self._get_top_logprobs(
|
2024-07-18 00:13:30 -07:00
|
|
|
step_top_logprobs, num_output_top_logprobs,
|
|
|
|
tokenizer)))
|
2024-05-30 11:52:14 +02:00
|
|
|
|
|
|
|
return ChatCompletionLogProbs(content=logprobs_content)
|