-
Notifications
You must be signed in to change notification settings - Fork 687
Expand file tree
/
Copy pathapi_server.py
More file actions
1558 lines (1340 loc) · 65.4 KB
/
api_server.py
File metadata and controls
1558 lines (1340 loc) · 65.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) OpenMMLab. All rights reserved.
# yapf: disable
import asyncio
import copy
import json
import os
import re
import time
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from functools import partial
from http import HTTPStatus
from typing import Literal
import uvicorn
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, Response, StreamingResponse
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.routing import Mount
from lmdeploy.archs import get_task
from lmdeploy.messages import (
GenerationConfig,
LogitsProcessor,
PytorchEngineConfig,
SpeculativeConfig,
TurbomindEngineConfig,
)
from lmdeploy.metrics.metrics_processor import metrics_processor
from lmdeploy.model import ChatTemplateConfig
from lmdeploy.pytorch.disagg.config import DistServeEngineConfig
from lmdeploy.pytorch.disagg.conn.protocol import (
DistServeCacheFreeRequest,
DistServeConnectionRequest,
DistServeDropConnectionRequest,
DistServeInitRequest,
MigrationRequest,
)
from lmdeploy.serve.core import AsyncEngine
from lmdeploy.serve.openai.harmony_utils import GptOssChatParser
from lmdeploy.serve.openai.protocol import (
AbortRequest,
ChatCompletionRequest,
ChatCompletionResponse, # noqa: E501
ChatCompletionResponseChoice,
ChatCompletionResponseStreamChoice,
ChatCompletionStreamResponse,
ChatCompletionTokenLogprob,
ChatMessage,
ChoiceLogprobs,
CompletionRequest,
CompletionResponse,
CompletionResponseChoice,
CompletionResponseStreamChoice,
CompletionStreamResponse,
DeltaMessage,
EmbeddingsRequest,
EncodeRequest,
EncodeResponse,
ErrorResponse,
GenerateReqInput,
GenerateReqMetaOutput,
GenerateReqOutput,
LogProbs,
ModelCard,
ModelList,
ModelPermission,
PoolingRequest,
PoolingResponse,
TopLogprob,
UpdateParamsRequest,
UsageInfo,
)
from lmdeploy.serve.openai.reasoning_parser.reasoning_parser import ReasoningParser, ReasoningParserManager
from lmdeploy.serve.openai.tool_parser.tool_parser import ToolParser, ToolParserManager
from lmdeploy.serve.utils.server_utils import validate_json_request
from lmdeploy.tokenizer import DetokenizeState, Tokenizer
from lmdeploy.utils import get_logger
# yapf: enable
logger = get_logger('lmdeploy')
class VariableInterface:
"""A IO interface maintaining variables."""
async_engine: AsyncEngine = None
request_hosts = []
# following are for registering to proxy server
proxy_url: str | None = None
api_server_url: str | None = None
# following are for reasoning parsers
reasoning_parser: ReasoningParser | None = None
# following is for tool parsers
tool_parser: ToolParser | None = None
allow_terminate_by_client: bool = False
enable_abort_handling: bool = False
@staticmethod
def get_session(session_id: int) -> int:
session_mgr = VariableInterface.get_session_manager()
if session_id == -1:
return session_mgr.get()
else:
return session_mgr.get(session_id)
@staticmethod
def get_session_manager():
return VariableInterface.async_engine.session_mgr
@staticmethod
def get_engine_config():
return VariableInterface.async_engine.backend_config
router = APIRouter()
server_context = VariableInterface()
def get_model_list():
"""Available models.
If it is a slora serving. The model list would be [model_name, adapter_name1, adapter_name2, ...]
"""
model_names = [VariableInterface.async_engine.model_name]
cfg = VariableInterface.async_engine.backend_config
model_names += getattr(cfg, 'adapters', None) or []
return model_names
@router.get('/v1/models')
def available_models():
"""Show available models."""
model_cards = []
for model_name in get_model_list():
model_cards.append(ModelCard(id=model_name, root=model_name, permission=[ModelPermission()]))
return ModelList(data=model_cards)
def create_error_response(status: HTTPStatus, message: str, error_type='invalid_request_error'):
"""Create error response according to http status and message.
Args:
status (HTTPStatus): HTTP status codes and reason phrases
message (str): error message
error_type (str): error type
"""
return JSONResponse(ErrorResponse(message=message, type=error_type, code=status.value).model_dump(),
status_code=status.value)
def check_request(request) -> JSONResponse | None:
"""Check if a request is valid."""
if hasattr(request, 'model') and request.model not in get_model_list():
return create_error_response(HTTPStatus.NOT_FOUND, f'The model {request.model!r} does not exist.')
# Import the appropriate check function based on request type
if isinstance(request, ChatCompletionRequest):
from .serving_chat_completion import check_request
check_func = check_request
elif isinstance(request, CompletionRequest):
from .serving_completion import check_request
check_func = check_request
elif isinstance(request, GenerateReqInput):
from .serving_generate import check_request
check_func = check_request
else:
# Define an async function that always returns success
def always_success(req, server_context):
return ''
check_func = always_success
error_msg = check_func(request, server_context)
if error_msg:
return create_error_response(HTTPStatus.BAD_REQUEST, error_msg)
return None
def _create_completion_logprobs(tokenizer: Tokenizer,
token_ids: list[int] | None = None,
logprobs: list[dict[int, float]] | None = None,
skip_special_tokens: bool = True,
offset: int = 0,
all_token_ids: list[int] | None = None,
state: DetokenizeState = None,
spaces_between_special_tokens: bool = True):
"""Create openai LogProbs for completion.
Args:
tokenizer (Tokenizer): tokenizer.
token_ids (list[int]): output token ids.
logprobs (list[dict[int, float]]): the top logprobs for each output
position.
skip_special_tokens (bool): Whether or not to remove special tokens
in the decoding. Default to be True.
offset (int): text offset.
all_token_ids (int): the history output token ids.
state (DetokenizeState): tokenizer decode state.
spaces_between_special_tokens (bool): Whether or not to add spaces
around special tokens. The behavior of Fast tokenizers is to have
this to False. This is setup to True in slow tokenizers.
"""
if logprobs is None or len(logprobs) == 0:
return None, None, None, None
if all_token_ids is None:
all_token_ids = []
if state is None:
state = DetokenizeState()
out_logprobs = LogProbs()
out_logprobs.top_logprobs = []
for token_id, tops in zip(token_ids, logprobs):
out_logprobs.text_offset.append(offset)
out_logprobs.token_logprobs.append(tops[token_id])
res = {}
out_state = None
for top_id, prob in tops.items():
response, _state = tokenizer.detokenize_incrementally(
all_token_ids + [top_id],
copy.deepcopy(state),
skip_special_tokens=skip_special_tokens,
spaces_between_special_tokens=spaces_between_special_tokens)
res[response] = prob
if top_id == token_id:
out_state = _state
offset += len(response)
out_logprobs.tokens.append(response)
out_logprobs.top_logprobs.append(res)
state = out_state
all_token_ids.append(token_id)
return out_logprobs, offset, all_token_ids, state
def _create_chat_completion_logprobs(tokenizer: Tokenizer,
token_ids: list[int] | None = None,
logprobs: list[dict[int, float]] | None = None):
"""Create openai LogProbs for chat.completion.
Args:
tokenizer (Tokenizer): tokenizer.
token_ids (list[int]): output token ids.
logprobs (list[dict[int, float]]): the top logprobs for each output
position.
Returns:
ChoiceLogprobs: logprob result.
"""
if token_ids is None or logprobs is None:
return None
content: list[ChatCompletionTokenLogprob] = []
for token_id, tops in zip(token_ids, logprobs):
item = ChatCompletionTokenLogprob(token='', bytes=[], logprob=0.0, top_logprobs=[])
for top_id, prob in tops.items():
token = tokenizer.model.model.convert_ids_to_tokens(top_id)
if isinstance(token, bytes):
_bytes = list(token)
token = token.decode('utf-8', errors='backslashreplace')
else:
_bytes = list(token.encode()) # token is str
if top_id == token_id:
item.token = token
item.bytes = _bytes
item.logprob = prob
else:
item.top_logprobs.append(TopLogprob(token=token, bytes=_bytes, logprob=prob))
content.append(item)
return ChoiceLogprobs(content=content)
@router.get('/health')
async def health() -> Response:
"""Health check."""
return Response(status_code=200)
@router.get('/terminate')
async def terminate():
"""Terminate server."""
import signal
if not VariableInterface.allow_terminate_by_client:
return create_error_response(
HTTPStatus.BAD_REQUEST,
'The server can not be terminated. Please add --allow-terminate-by-client when start the server.')
os.kill(os.getpid(), signal.SIGTERM)
return Response(status_code=200)
# modified from https://github.com/vllm-project/vllm/blob/v0.5.4/vllm/entrypoints/openai/logits_processors.py#L51 # noqa
def logit_bias_logits_processor(logit_bias: dict[int, float] | dict[str, float], tokenizer) -> LogitsProcessor:
try:
# Convert token_id to integer
# Clamp the bias between -100 and 100 per OpenAI API spec
clamped_logit_bias: dict[int, float] = {
int(token_id): min(100.0, max(-100.0, bias))
for token_id, bias in logit_bias.items()
}
except ValueError as exc:
raise ValueError('Found token_id in logit_bias that is not '
'an integer or string representing an integer') from exc
# Check if token_id is within the vocab size
for token_id, bias in clamped_logit_bias.items():
if token_id < 0 or token_id >= tokenizer.vocab_size:
raise ValueError(f'token_id {token_id} in logit_bias contains '
'out-of-vocab token id')
def _logit_bias_processor(
logit_bias,
token_ids,
logits,
):
for token_id, bias in logit_bias.items():
logits[token_id] = logits[token_id] + bias
return logits
return partial(_logit_bias_processor, clamped_logit_bias)
@router.post('/v1/chat/completions', dependencies=[Depends(validate_json_request)])
async def chat_completions_v1(request: ChatCompletionRequest, raw_request: Request = None):
"""Completion API similar to OpenAI's API.
Refer to https://platform.openai.com/docs/api-reference/chat/create
for the API specification.
The request should be a JSON object with the following fields:
- **model**: model name. Available from /v1/models.
- **messages**: string prompt or chat history in OpenAI format. Chat history example:
``[{"role": "user", "content": "hi"}]``.
- **temperature** (float): to modulate the next token probability
- **top_p** (float): If set to float < 1, only the smallest set of most
probable tokens with probabilities that add up to top_p or higher
are kept for generation.
- **n** (int): How many chat completion choices to generate for each input
message. **Only support one here**.
- **stream**: whether to stream the results or not. Default to false.
- **stream_options**: Options for streaming response. Only set this when you
set stream: true.
- **max_completion_tokens** (int | None): output token nums. Default to None.
- **max_tokens** (int | None): output token nums. Default to None.
Deprecated: Use max_completion_tokens instead.
- **repetition_penalty** (float): The parameter for repetition penalty.
1.0 means no penalty
- **stop** (str | list[str] | None): To stop generating further
tokens. Only accept stop words that's encoded to one token idex.
- **response_format** (dict | None): To generate response according to given
schema. Examples:
.. code-block:: json
{
"type": "json_schema",
"json_schema":{
"name": "test",
"schema":{
"properties":{
"name":{"type":"string"}
},
"required":["name"],
"type":"object"
}
}
}
or ``{"type": "regex_schema", "regex_schema": "call me [A-Za-z]{1,10}"}``
- **logit_bias** (dict): Bias to logits. Only supported in pytorch engine.
- **tools** (list): A list of tools the model may call. Currently, only
internlm2 functions are supported as a tool. Use this to specify a
list of functions for which the model can generate JSON inputs.
- **tool_choice** (str | object): Controls which (if any) tool is called by
the model. `none` means the model will not call any tool and instead
generates a message. Specifying a particular tool via
``{"type": "function", "function": {"name": "my_function"}}``
forces the model to call that tool. `auto` or `required` will put all
the tools informationto the model.
Additional arguments supported by LMDeploy:
- **top_k** (int): The number of the highest probability vocabulary
tokens to keep for top-k-filtering
- **ignore_eos** (bool): indicator for ignoring eos
- **skip_special_tokens** (bool): Whether or not to remove special tokens
in the decoding. Default to be True.
- **spaces_between_special_tokens** (bool): Whether or not to add spaces
around special tokens. The behavior of Fast tokenizers is to have
this to False. This is setup to True in slow tokenizers.
- **min_new_tokens** (int): To generate at least numbers of tokens.
- **min_p** (float): Minimum token probability, which will be scaled by the
probability of the most likely token. It must be a value between
0 and 1. Typical values are in the 0.01-0.2 range, comparably
selective as setting `top_p` in the 0.99-0.8 range (use the
opposite of normal `top_p` values)
Currently we do not support the following features:
- **presence_penalty** (replaced with repetition_penalty)
- **frequency_penalty** (replaced with repetition_penalty)
"""
error_check_ret = check_request(request)
if error_check_ret is not None:
return error_check_ret
if VariableInterface.tool_parser is not None:
request = VariableInterface.tool_parser.adjust_request(request)
session = VariableInterface.get_session(request.session_id)
json_request = await raw_request.json()
migration_request = json_request.pop('migration_request', None)
with_cache = json_request.pop('with_cache', False)
preserve_cache = json_request.pop('preserve_cache', False)
if migration_request:
migration_request = MigrationRequest.model_validate(migration_request)
model_name = request.model
adapter_name = None
if model_name != VariableInterface.async_engine.model_name:
adapter_name = model_name # got a adapter name
request_id = str(session.session_id)
created_time = int(time.time())
gpt_oss_parser = None
if VariableInterface.async_engine.arch == 'GptOssForCausalLM':
gpt_oss_parser = GptOssChatParser()
if isinstance(request.stop, str):
request.stop = [request.stop]
gen_logprobs, logits_processors = None, None
if request.logprobs and request.top_logprobs:
gen_logprobs = request.top_logprobs
response_format = None
if request.response_format and request.response_format.type != 'text':
response_format = request.response_format.model_dump()
if request.logit_bias is not None:
try:
logits_processors = [
logit_bias_logits_processor(request.logit_bias, VariableInterface.async_engine.tokenizer.model)
]
except Exception as e:
return create_error_response(HTTPStatus.BAD_REQUEST, str(e))
random_seed = request.seed if request.seed else None
max_new_tokens = (request.max_completion_tokens if request.max_completion_tokens else request.max_tokens)
gen_config = GenerationConfig(
max_new_tokens=max_new_tokens,
do_sample=True,
logprobs=gen_logprobs,
top_k=request.top_k,
top_p=request.top_p,
temperature=request.temperature,
repetition_penalty=request.repetition_penalty,
ignore_eos=request.ignore_eos,
stop_words=request.stop,
include_stop_str_in_output=request.include_stop_str_in_output,
skip_special_tokens=request.skip_special_tokens,
response_format=response_format,
logits_processors=logits_processors,
min_new_tokens=request.min_new_tokens,
min_p=request.min_p,
random_seed=random_seed,
spaces_between_special_tokens=request.spaces_between_special_tokens,
migration_request=migration_request,
with_cache=with_cache,
preserve_cache=preserve_cache,
)
tools = None
if request.tools and request.tool_choice != 'none':
gen_config.skip_special_tokens = False
# internlm2 only uses contents inside function regardless of 'type'
if not isinstance(request.tool_choice, str):
if gpt_oss_parser:
tools = [
item.model_dump() for item in request.tools
if item.function.name == request.tool_choice.function.name
]
else:
tools = [
item.function.model_dump() for item in request.tools
if item.function.name == request.tool_choice.function.name
]
else:
if gpt_oss_parser:
tools = [item.model_dump() for item in request.tools]
else:
tools = [item.function.model_dump() for item in request.tools]
# text completion for string input
do_preprocess = False if isinstance(request.messages, str) else request.do_preprocess
chat_template_kwargs = request.chat_template_kwargs or {}
if request.enable_thinking is not None:
logger.warning('`enable_thinking` will be deprecated in the future, '
'please use `chat_template_kwargs` instead.')
if chat_template_kwargs.get('enable_thinking') is None:
chat_template_kwargs['enable_thinking'] = request.enable_thinking
else:
logger.warning('`enable_thinking` in `chat_template_kwargs` will override the value in request.')
enable_thinking = chat_template_kwargs.get('enable_thinking', None)
result_generator = VariableInterface.async_engine.generate(
request.messages,
session,
gen_config=gen_config,
tools=tools,
reasoning_effort=request.reasoning_effort,
stream_response=True, # always use stream to enable batching
sequence_start=True,
sequence_end=True,
do_preprocess=do_preprocess,
adapter_name=adapter_name,
chat_template_kwargs=chat_template_kwargs or None,
media_io_kwargs=request.media_io_kwargs,
mm_processor_kwargs=request.mm_processor_kwargs)
def create_stream_response_json(index: int,
delta_message: DeltaMessage,
finish_reason: str | None = None,
logprobs: LogProbs | None = None,
usage: UsageInfo | None = None) -> str:
choice_data = ChatCompletionResponseStreamChoice(index=index,
delta=delta_message,
finish_reason=finish_reason,
logprobs=logprobs)
response = ChatCompletionStreamResponse(
id=request_id,
created=created_time,
model=model_name,
choices=[choice_data],
usage=usage,
)
response_json = response.model_dump_json()
return response_json
async def completion_stream_generator() -> AsyncGenerator[str, None]:
previous_text = ''
current_text = ''
previous_token_ids = []
current_token_ids = []
delta_token_ids = []
has_parser = VariableInterface.tool_parser is not None or VariableInterface.reasoning_parser is not None
streaming_tools = False
async for res in result_generator:
logprobs, usage = None, None
if gen_logprobs and res.logprobs:
logprobs = _create_chat_completion_logprobs(VariableInterface.async_engine.tokenizer, res.token_ids,
res.logprobs)
# Only stream chunk `usage` in the final chunk according to OpenAI API spec
if (res.finish_reason and request.stream_options and request.stream_options.include_usage):
total_tokens = sum([res.input_token_len, res.generate_token_len])
usage = UsageInfo(
prompt_tokens=res.input_token_len,
completion_tokens=res.generate_token_len,
total_tokens=total_tokens,
)
delta_token_ids = res.token_ids if res.token_ids is not None else []
if gpt_oss_parser:
delta_message = gpt_oss_parser.parse_streaming(res.token_ids)
if res.finish_reason == 'stop' and len(delta_message.tool_calls) > 0:
res.finish_reason = 'tool_calls'
else:
delta_message = DeltaMessage(role='assistant', content=res.response)
if has_parser:
current_text = current_text + res.response
current_token_ids = current_token_ids + delta_token_ids
if request.tool_choice != 'none' and VariableInterface.tool_parser is not None:
if res.finish_reason == 'stop' and streaming_tools is True:
res.finish_reason = 'tool_calls'
tool_delta = VariableInterface.tool_parser.extract_tool_calls_streaming(
previous_text=previous_text,
current_text=current_text,
delta_text=delta_message.content,
previous_token_ids=previous_token_ids,
current_token_ids=current_token_ids,
delta_token_ids=delta_token_ids,
request=request)
if tool_delta is not None:
delta_message.tool_calls = tool_delta.tool_calls
delta_message.content = tool_delta.content
if isinstance(tool_delta.tool_calls, list) and len(tool_delta.tool_calls):
streaming_tools = True
elif (request.tool_choice != 'none' and request.tools is not None
and VariableInterface.tool_parser is None):
logger.error('Please launch the api_server with --tool-call-parser if you want to use tool.')
if VariableInterface.reasoning_parser is not None and enable_thinking is not False:
reasoning_delta = VariableInterface.reasoning_parser.extract_reasoning_content_streaming(
previous_text=previous_text,
current_text=current_text,
delta_text=delta_message.content or '',
previous_token_ids=previous_token_ids,
current_token_ids=current_token_ids,
delta_token_ids=delta_token_ids)
if reasoning_delta is not None:
delta_message.reasoning_content = reasoning_delta.reasoning_content
delta_message.content = reasoning_delta.content
if has_parser:
previous_text = current_text
previous_token_ids = current_token_ids
if request.return_token_ids:
delta_message.gen_tokens = delta_token_ids
response_json = create_stream_response_json(index=0,
delta_message=delta_message,
finish_reason=res.finish_reason,
logprobs=logprobs,
usage=usage)
if res.cache_block_ids is not None:
response_json['cache_block_ids'] = res.cache_block_ids
response_json['remote_token_ids'] = res.token_ids
yield f'data: {response_json}\n\n'
yield 'data: [DONE]\n\n'
# Streaming response
if request.stream:
return StreamingResponse(completion_stream_generator(), media_type='text/event-stream')
# Non-streaming response
final_logprobs = []
final_token_ids = []
final_res = None
text = ''
cache_block_ids = []
remote_token_ids = []
async for res in result_generator:
if await raw_request.is_disconnected():
# Abort the request if the client disconnects.
await session.async_abort()
return create_error_response(HTTPStatus.BAD_REQUEST, 'Client disconnected')
final_res = res
text += res.response
if res.token_ids:
final_token_ids.extend(res.token_ids)
if res.logprobs:
final_logprobs.extend(res.logprobs)
cache_block_ids.append(res.cache_block_ids)
remote_token_ids.append(res.token_ids)
if gpt_oss_parser:
message = gpt_oss_parser.parse_full(final_token_ids)
if final_res.finish_reason == 'stop' and len(message.tool_calls) > 0:
final_res.finish_reason = 'tool_calls'
else:
tool_calls = None
reasoning_content = None
if request.tool_choice != 'none' and VariableInterface.tool_parser is not None:
try:
tool_call_info = VariableInterface.tool_parser.extract_tool_calls(text, request=request)
text, tool_calls = tool_call_info.content, tool_call_info.tool_calls
if isinstance(tool_calls, list) and len(tool_calls):
if final_res.finish_reason == 'stop':
final_res.finish_reason = 'tool_calls'
except Exception as e:
logger.error(f'Failed to parse {text}. Exception: {e}.')
return create_error_response(HTTPStatus.BAD_REQUEST, 'Failed to parse fc related info to json format!')
elif request.tool_choice != 'none' and request.tools is not None and VariableInterface.tool_parser is None:
logger.error('Please launch the api_server with --tool-call-parser if you want to use tool.')
if VariableInterface.reasoning_parser is not None and enable_thinking is not False:
reasoning_content, text = VariableInterface.reasoning_parser.extract_reasoning_content(text, request)
message = ChatMessage(role='assistant',
content=text,
tool_calls=tool_calls,
reasoning_content=reasoning_content)
logprobs = None
if gen_logprobs and len(final_logprobs):
logprobs = _create_chat_completion_logprobs(VariableInterface.async_engine.tokenizer, final_token_ids,
final_logprobs)
assert final_res is not None
choices = []
if request.return_token_ids:
message.gen_tokens = final_token_ids
choice_data = ChatCompletionResponseChoice(
index=0,
message=message,
logprobs=logprobs,
finish_reason=final_res.finish_reason,
)
choices.append(choice_data)
if with_cache:
cache_block_ids = cache_block_ids[0]
remote_token_ids = [remote_token_ids[0][-1]]
total_tokens = sum([final_res.input_token_len, final_res.generate_token_len])
usage = UsageInfo(
prompt_tokens=final_res.input_token_len,
completion_tokens=final_res.generate_token_len,
total_tokens=total_tokens,
)
response = ChatCompletionResponse(
id=request_id,
created=created_time,
model=model_name,
choices=choices,
usage=usage,
).model_dump()
if with_cache:
response['cache_block_ids'] = cache_block_ids
response['remote_token_ids'] = remote_token_ids
return response
@router.post('/v1/completions', dependencies=[Depends(validate_json_request)])
async def completions_v1(request: CompletionRequest, raw_request: Request = None):
"""Completion API similar to OpenAI's API.
Go to https://platform.openai.com/docs/api-reference/completions/create
for the API specification.
The request should be a JSON object with the following fields:
- **model** (str): model name. Available from /v1/models.
- **prompt** (str): the input prompt.
- **suffix** (str): The suffix that comes after a completion of inserted text.
- **max_completion_tokens** (int | None): output token nums. Default to None.
- **max_tokens** (int | None): output token nums. Default to 16.
Deprecated: Use max_completion_tokens instead.
- **temperature** (float): to modulate the next token probability
- **top_p** (float): If set to float < 1, only the smallest set of most
probable tokens with probabilities that add up to top_p or higher
are kept for generation.
- **n** (int): How many chat completion choices to generate for each input
message. **Only support one here**.
- **stream**: whether to stream the results or not. Default to false.
- **stream_options**: Options for streaming response. Only set this when you
set stream: true.
- **repetition_penalty** (float): The parameter for repetition penalty.
1.0 means no penalty
- **user** (str): A unique identifier representing your end-user.
- **stop** (str | list[str] | None): To stop generating further
tokens. Only accept stop words that's encoded to one token idex.
Additional arguments supported by LMDeploy:
- **ignore_eos** (bool): indicator for ignoring eos
- **skip_special_tokens** (bool): Whether or not to remove special tokens
in the decoding. Default to be True.
- **spaces_between_special_tokens** (bool): Whether or not to add spaces
around special tokens. The behavior of Fast tokenizers is to have
this to False. This is setup to True in slow tokenizers.
- **top_k** (int): The number of the highest probability vocabulary
tokens to keep for top-k-filtering
- **min_p** (float): Minimum token probability, which will be scaled by the
probability of the most likely token. It must be a value between
0 and 1. Typical values are in the 0.01-0.2 range, comparably
selective as setting `top_p` in the 0.99-0.8 range (use the
opposite of normal `top_p` values)
Currently we do not support the following features:
- **logprobs** (not supported yet)
- **presence_penalty** (replaced with repetition_penalty)
- **frequency_penalty** (replaced with repetition_penalty)
"""
error_check_ret = check_request(request)
if error_check_ret is not None:
return error_check_ret
json_request = await raw_request.json()
migration_request = json_request.pop('migration_request', None)
with_cache = json_request.pop('with_cache', False)
preserve_cache = json_request.pop('preserve_cache', False)
if migration_request:
migration_request = MigrationRequest.model_validate(migration_request)
model_name = request.model
adapter_name = None
if model_name != VariableInterface.async_engine.model_name:
adapter_name = model_name # got a adapter name
request_id = str(request.session_id)
created_time = int(time.time())
sessions = []
if isinstance(request.prompt, str):
request.prompt = [request.prompt]
sessions.append(VariableInterface.get_session(request.session_id))
elif isinstance(request.prompt, list):
for i in range(len(request.prompt)):
sessions.append(VariableInterface.get_session(i + 1))
if isinstance(request.stop, str):
request.stop = [request.stop]
random_seed = request.seed if request.seed else None
max_new_tokens = (request.max_completion_tokens if request.max_completion_tokens else request.max_tokens)
gen_config = GenerationConfig(
max_new_tokens=max_new_tokens,
do_sample=True,
logprobs=request.logprobs,
top_k=request.top_k,
top_p=request.top_p,
temperature=request.temperature,
repetition_penalty=request.repetition_penalty,
ignore_eos=request.ignore_eos,
stop_words=request.stop,
skip_special_tokens=request.skip_special_tokens,
min_p=request.min_p,
random_seed=random_seed,
spaces_between_special_tokens=request.spaces_between_special_tokens,
migration_request=migration_request,
with_cache=with_cache,
preserve_cache=preserve_cache,
)
generators = []
for prompt, session in zip(request.prompt, sessions):
result_generator = VariableInterface.async_engine.generate(
prompt,
session,
gen_config=gen_config,
stream_response=True, # always use stream to enable batching
sequence_start=True,
sequence_end=True,
do_preprocess=False,
adapter_name=adapter_name)
generators.append(result_generator)
def create_stream_response_json(index: int,
text: str,
finish_reason: str | None = None,
logprobs: LogProbs | None = None,
gen_tokens: list[int] | None = None,
usage: UsageInfo | None = None) -> str:
choice_data = CompletionResponseStreamChoice(index=index,
text=text,
gen_tokens=gen_tokens,
finish_reason=finish_reason,
logprobs=logprobs)
response = CompletionStreamResponse(
id=request_id,
created=created_time,
model=model_name,
choices=[choice_data],
usage=usage,
)
response_json = response.model_dump()
return response_json
async def completion_stream_generator() -> AsyncGenerator[str, None]:
# First chunk with role
for generator in generators:
offset = 0
all_token_ids = []
state = DetokenizeState()
async for res in generator:
logprobs = None
usage = None
if request.logprobs and res.logprobs:
logprobs, offset, all_token_ids, state = _create_completion_logprobs( # noqa E501
VariableInterface.async_engine.tokenizer, res.token_ids, res.logprobs,
gen_config.skip_special_tokens, offset, all_token_ids, state,
gen_config.spaces_between_special_tokens)
# Only stream chunk `usage` in the final chunk according to OpenAI API spec
if (res.finish_reason and request.stream_options and request.stream_options.include_usage):
final_res = res
total_tokens = sum([final_res.input_token_len, final_res.generate_token_len])
usage = UsageInfo(
prompt_tokens=final_res.input_token_len,
completion_tokens=final_res.generate_token_len,
total_tokens=total_tokens,
)
gen_tokens = None
if request.return_token_ids:
gen_tokens = res.token_ids or []
response_json = create_stream_response_json(index=0,
text=res.response,
gen_tokens=gen_tokens,
finish_reason=res.finish_reason,
logprobs=logprobs,
usage=usage)
if res.cache_block_ids is not None:
response_json['cache_block_ids'] = res.cache_block_ids
response_json['remote_token_ids'] = res.token_ids
yield f'data: {json.dumps(response_json)}\n\n'
yield 'data: [DONE]\n\n'
# Streaming response
if request.stream:
return StreamingResponse(completion_stream_generator(), media_type='text/event-stream')
# Non-streaming response
usage = UsageInfo()
choices = [None] * len(generators)
cache_block_ids = []
remote_token_ids = []
async def _inner_call(i, generator):
nonlocal cache_block_ids, remote_token_ids
final_logprobs = []
final_token_ids = []
final_res = None
text = ''
async for res in generator:
if await raw_request.is_disconnected():
# Abort the request if the client disconnects.
await VariableInterface.async_engine.stop_session(request.session_id)
return create_error_response(HTTPStatus.BAD_REQUEST, 'Client disconnected')
final_res = res
text += res.response
cache_block_ids.append(res.cache_block_ids)
remote_token_ids.append(res.token_ids)
if res.token_ids:
final_token_ids.extend(res.token_ids)
if res.logprobs:
final_logprobs.extend(res.logprobs)
logprobs = None
if request.logprobs and len(final_logprobs):
logprobs, _, _, _ = _create_completion_logprobs(
VariableInterface.async_engine.tokenizer,
final_token_ids,
final_logprobs,
gen_config.skip_special_tokens,
spaces_between_special_tokens=gen_config.spaces_between_special_tokens)
assert final_res is not None
choice_data = CompletionResponseChoice(index=i,
text=text,
finish_reason=final_res.finish_reason,
logprobs=logprobs,
gen_tokens=final_token_ids if request.return_token_ids else None)
choices[i] = choice_data
if with_cache:
cache_block_ids = cache_block_ids[0]
remote_token_ids = [remote_token_ids[0][-1]]
total_tokens = sum([final_res.input_token_len, final_res.generate_token_len])
usage.prompt_tokens += final_res.input_token_len
usage.completion_tokens += final_res.generate_token_len
usage.total_tokens += total_tokens
await asyncio.gather(*[_inner_call(i, generators[i]) for i in range(len(generators))])
response = CompletionResponse(
id=request_id,
created=created_time,
model=model_name,
choices=choices,
usage=usage,
).model_dump()
if with_cache:
response['cache_block_ids'] = cache_block_ids
response['remote_token_ids'] = remote_token_ids
return response
@router.post('/generate', dependencies=[Depends(validate_json_request)])
async def generate(request: GenerateReqInput, raw_request: Request = None):
error_check_ret = check_request(request)
if error_check_ret is not None:
return error_check_ret
session = VariableInterface.get_session(request.session_id)
prompt = request.prompt
input_ids = request.input_ids
image_data = request.image_data
if image_data is not None:
# convert to openai format
image_input = []
if not isinstance(image_data, list):
image_data = [image_data]
for img in image_data:
if isinstance(img, str):
image_input.append(dict(type='image_url', image_url=dict(url=img)))
else:
image_input.append(dict(type='image_url', image_url=img))
text_input = dict(type='text', text=prompt if prompt else input_ids)
prompt = [dict(role='user', content=[text_input] + image_input)]
input_ids = None
gen_config = GenerationConfig(
max_new_tokens=request.max_tokens,
do_sample=True,
logprobs=1 if request.return_logprob else None,
top_k=request.top_k,
top_p=request.top_p,
min_p=request.min_p,
temperature=request.temperature,
repetition_penalty=request.repetition_penalty,
ignore_eos=request.ignore_eos,
stop_words=request.stop,
stop_token_ids=request.stop_token_ids,
skip_special_tokens=request.skip_special_tokens,
spaces_between_special_tokens=request.spaces_between_special_tokens,
include_stop_str_in_output=request.include_stop_str_in_output,
return_routed_experts=request.return_routed_experts,