serving_chat.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import time
  2. import codecs
  3. from fastapi import Request
  4. from typing import AsyncGenerator, AsyncIterator, Optional, List, Union
  5. from loguru import logger
  6. from aphrodite.common.utils import random_uuid
  7. from aphrodite.engine.async_aphrodite import AsyncAphrodite
  8. from aphrodite.endpoints.openai.protocol import (
  9. ChatCompletionRequest, ChatCompletionResponse,
  10. ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice,
  11. ChatCompletionStreamResponse, ChatMessage, DeltaMessage, ErrorResponse,
  12. UsageInfo)
  13. from aphrodite.common.outputs import RequestOutput
  14. from aphrodite.endpoints.openai.serving_engine import OpenAIServing, LoRA
  15. from aphrodite.modeling.outlines_decoding import get_guided_decoding_logits_processor
  16. class OpenAIServingChat(OpenAIServing):
  17. def __init__(self,
  18. engine: AsyncAphrodite,
  19. served_model: str,
  20. response_role: str,
  21. lora_modules: Optional[List[LoRA]] = None,
  22. chat_template=None):
  23. super().__init__(engine=engine,
  24. served_model=served_model,
  25. lora_modules=lora_modules)
  26. self.response_role = response_role
  27. self._load_chat_template(chat_template)
  28. async def create_chat_completion(
  29. self, request: ChatCompletionRequest, raw_request: Request
  30. ) -> Union[ErrorResponse, AsyncGenerator[str, None],
  31. ChatCompletionResponse]:
  32. """Completion API similar to OpenAI's API.
  33. See https://platform.openai.com/docs/api-reference/chat/create
  34. for the API specification. This API mimics the OpenAI ChatCompletion API.
  35. NOTE: Currently we do not support the following feature:
  36. - function_call (Users should implement this by themselves)
  37. """
  38. error_check_ret = await self._check_model(request)
  39. if error_check_ret is not None:
  40. return error_check_ret
  41. try:
  42. prompt = self.tokenizer.apply_chat_template(
  43. conversation=request.messages,
  44. tokenize=False,
  45. add_generation_prompt=request.add_generation_prompt)
  46. except Exception as e:
  47. logger.error(
  48. f"Error in applying chat template from request: {str(e)}")
  49. return self.create_error_response(str(e))
  50. request_id = f"cmpl-{random_uuid()}"
  51. try:
  52. token_ids = self._validate_prompt_and_tokenize(request,
  53. prompt=prompt)
  54. sampling_params = request.to_sampling_params()
  55. lora_request = self._maybe_get_lora(request)
  56. guided_decode_logits_processor = (
  57. await get_guided_decoding_logits_processor(
  58. request, self.engine.get_tokenizer()))
  59. if guided_decode_logits_processor:
  60. if sampling_params.logits_processors is None:
  61. sampling_params.logits_processors = []
  62. sampling_params.logits_processors.append(
  63. guided_decode_logits_processor)
  64. except ValueError as e:
  65. return self.create_error_response(str(e))
  66. result_generator = self.engine.generate(prompt, sampling_params,
  67. request_id, token_ids,
  68. lora_request)
  69. # Streaming response
  70. if request.stream:
  71. return self.chat_completion_stream_generator(
  72. request, result_generator, request_id)
  73. else:
  74. try:
  75. return await self.chat_completion_full_generator(
  76. request, raw_request, result_generator, request_id)
  77. except ValueError as e:
  78. # TODO: Use an aphrodite-specific Validation Error
  79. return self.create_error_response(str(e))
  80. def get_chat_request_role(self, request: ChatCompletionRequest) -> str:
  81. if request.add_generation_prompt:
  82. return self.response_role
  83. else:
  84. return request.messages[-1]["role"]
  85. async def chat_completion_stream_generator(
  86. self, request: ChatCompletionRequest,
  87. result_generator: AsyncIterator[RequestOutput], request_id: str
  88. ) -> Union[ErrorResponse, AsyncGenerator[str, None]]:
  89. model_name = request.model
  90. created_time = int(time.monotonic())
  91. chunk_object_type = "chat.completion.chunk"
  92. first_iteration = True
  93. # Send response for each token for each request.n (index)
  94. previous_texts = [""] * request.n
  95. previous_num_tokens = [0] * request.n
  96. finish_reason_sent = [False] * request.n
  97. try:
  98. async for res in result_generator:
  99. res: RequestOutput
  100. # We need to do it here, because if there are exceptions in
  101. # the result_generator, it needs to be sent as the FIRST
  102. # response (by the try...catch).
  103. if first_iteration:
  104. # Send first response for each request.n (index) with the role
  105. role = self.get_chat_request_role(request)
  106. for i in range(request.n):
  107. choice_data = ChatCompletionResponseStreamChoice(
  108. index=i,
  109. delta=DeltaMessage(role=role),
  110. logprobs=None,
  111. finish_reason=None)
  112. chunk = ChatCompletionStreamResponse(
  113. id=request_id,
  114. object=chunk_object_type,
  115. created=created_time,
  116. choices=[choice_data],
  117. model=model_name)
  118. data = chunk.model_dump_json(exclude_unset=True)
  119. yield f"data: {data}\n\n"
  120. # Send response to echo the input portion of the last message
  121. if request.echo:
  122. last_msg_content = ""
  123. if request.messages and isinstance(
  124. request.messages,
  125. list) and request.messages[-1].get(
  126. "content") and request.messages[-1].get(
  127. "role") == role:
  128. last_msg_content = request.messages[-1]["content"]
  129. if last_msg_content:
  130. for i in range(request.n):
  131. choice_data = ChatCompletionResponseStreamChoice(
  132. index=i,
  133. delta=DeltaMessage(
  134. content=last_msg_content),
  135. finish_reason=None)
  136. chunk = ChatCompletionStreamResponse(
  137. id=request_id,
  138. object=chunk_object_type,
  139. created=created_time,
  140. choices=[choice_data],
  141. logprobs=None,
  142. model=model_name)
  143. data = chunk.model_dump_json(
  144. exclude_unset=True)
  145. yield f"data: {data}\n\n"
  146. first_iteration = False
  147. for output in res.outputs:
  148. i = output.index
  149. if finish_reason_sent[i]:
  150. continue
  151. delta_token_ids = output.token_ids[previous_num_tokens[i]:]
  152. top_logprobs = output.logprobs[
  153. previous_num_tokens[i]:] if output.logprobs else None
  154. if request.logprobs:
  155. logprobs = self._create_logprobs(
  156. token_ids=delta_token_ids,
  157. top_logprobs=top_logprobs,
  158. num_output_top_logprobs=request.logprobs,
  159. initial_text_offset=len(previous_texts[i]),
  160. )
  161. else:
  162. logprobs = None
  163. delta_text = output.text[len(previous_texts[i]):]
  164. previous_texts[i] = output.text
  165. previous_num_tokens[i] = len(output.token_ids)
  166. if output.finish_reason is None:
  167. # Send token-by-token response for each request.n
  168. choice_data = ChatCompletionResponseStreamChoice(
  169. index=i,
  170. delta=DeltaMessage(content=delta_text),
  171. logprobs=logprobs,
  172. finish_reason=None)
  173. chunk = ChatCompletionStreamResponse(
  174. id=request_id,
  175. object=chunk_object_type,
  176. created=created_time,
  177. choices=[choice_data],
  178. model=model_name)
  179. data = chunk.model_dump_json(exclude_unset=True)
  180. yield f"data: {data}\n\n"
  181. else:
  182. # Send the finish response for each request.n only once
  183. prompt_tokens = len(res.prompt_token_ids)
  184. final_usage = UsageInfo(
  185. prompt_tokens=prompt_tokens,
  186. completion_tokens=previous_num_tokens[i],
  187. total_tokens=prompt_tokens +
  188. previous_num_tokens[i],
  189. )
  190. choice_data = ChatCompletionResponseStreamChoice(
  191. index=i,
  192. delta=DeltaMessage(content=delta_text),
  193. logprobs=logprobs,
  194. finish_reason=output.finish_reason)
  195. chunk = ChatCompletionStreamResponse(
  196. id=request_id,
  197. object=chunk_object_type,
  198. created=created_time,
  199. choices=[choice_data],
  200. model=model_name)
  201. if final_usage is not None:
  202. chunk.usage = final_usage
  203. data = chunk.model_dump_json(exclude_unset=True,
  204. exclude_none=True)
  205. yield f"data: {data}\n\n"
  206. finish_reason_sent[i] = True
  207. except ValueError as e:
  208. # TODO: Use an aphrodite-specific Validation Error
  209. data = self.create_streaming_error_response(str(e))
  210. yield f"data: {data}\n\n"
  211. # Send the final done message after all response.n are finished
  212. yield "data: [DONE]\n\n"
  213. async def chat_completion_full_generator(
  214. self, request: ChatCompletionRequest, raw_request: Request,
  215. result_generator: AsyncIterator[RequestOutput],
  216. request_id: str) -> Union[ErrorResponse, ChatCompletionResponse]:
  217. model_name = request.model
  218. created_time = int(time.monotonic())
  219. final_res: RequestOutput = None
  220. async for res in result_generator:
  221. if await raw_request.is_disconnected():
  222. # Abort the request if the client disconnects.
  223. await self.engine.abort(request_id)
  224. return self.create_error_response("Client disconnected")
  225. final_res = res
  226. assert final_res is not None
  227. choices = []
  228. role = self.get_chat_request_role(request)
  229. for output in final_res.outputs:
  230. token_ids = output.token_ids
  231. top_logprobs = output.logprobs
  232. if request.logprobs:
  233. logprobs = self._create_logprobs(
  234. token_ids=token_ids,
  235. top_logprobs=top_logprobs,
  236. num_output_top_logprobs=request.logprobs,
  237. )
  238. else:
  239. logprobs = None
  240. choice_data = ChatCompletionResponseChoice(
  241. index=output.index,
  242. message=ChatMessage(role=role, content=output.text),
  243. logprobs=logprobs,
  244. finish_reason=output.finish_reason,
  245. )
  246. choices.append(choice_data)
  247. if request.echo:
  248. last_msg_content = ""
  249. if request.messages and isinstance(
  250. request.messages, list) and request.messages[-1].get(
  251. "content") and request.messages[-1].get(
  252. "role") == role:
  253. last_msg_content = request.messages[-1]["content"]
  254. for choice in choices:
  255. full_message = last_msg_content + choice.message.content
  256. choice.message.content = full_message
  257. num_prompt_tokens = len(final_res.prompt_token_ids)
  258. num_generated_tokens = sum(
  259. len(output.token_ids) for output in final_res.outputs)
  260. usage = UsageInfo(
  261. prompt_tokens=num_prompt_tokens,
  262. completion_tokens=num_generated_tokens,
  263. total_tokens=num_prompt_tokens + num_generated_tokens,
  264. )
  265. response = ChatCompletionResponse(
  266. id=request_id,
  267. created=created_time,
  268. model=model_name,
  269. choices=choices,
  270. usage=usage,
  271. )
  272. return response
  273. def _load_chat_template(self, chat_template):
  274. if chat_template is not None:
  275. try:
  276. with open(chat_template, "r") as f:
  277. self.tokenizer.chat_template = f.read()
  278. except OSError:
  279. # If opening a file fails, set chat template to be args to
  280. # ensure we decode so our escape are interpreted correctly
  281. self.tokenizer.chat_template = codecs.decode(
  282. chat_template, "unicode_escape")
  283. logger.info("Using the supplied chat template.")
  284. elif self.tokenizer.chat_template is not None:
  285. logger.info("Using the default chat template")
  286. else:
  287. logger.warning(
  288. "No chat template provided. Chat API will not work.")