sglang 0.4.7.post1__py3-none-any.whl → 0.4.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. sglang/bench_one_batch.py +8 -6
  2. sglang/srt/_custom_ops.py +2 -2
  3. sglang/srt/code_completion_parser.py +2 -44
  4. sglang/srt/constants.py +3 -0
  5. sglang/srt/conversation.py +13 -3
  6. sglang/srt/custom_op.py +5 -1
  7. sglang/srt/disaggregation/decode.py +22 -28
  8. sglang/srt/disaggregation/decode_schedule_batch_mixin.py +4 -3
  9. sglang/srt/disaggregation/mini_lb.py +34 -4
  10. sglang/srt/disaggregation/mooncake/conn.py +12 -16
  11. sglang/srt/disaggregation/prefill.py +17 -13
  12. sglang/srt/disaggregation/utils.py +46 -18
  13. sglang/srt/distributed/parallel_state.py +12 -4
  14. sglang/srt/entrypoints/engine.py +22 -28
  15. sglang/srt/entrypoints/http_server.py +149 -79
  16. sglang/srt/entrypoints/http_server_engine.py +0 -3
  17. sglang/srt/entrypoints/openai/__init__.py +0 -0
  18. sglang/srt/{openai_api → entrypoints/openai}/protocol.py +67 -29
  19. sglang/srt/entrypoints/openai/serving_base.py +149 -0
  20. sglang/srt/entrypoints/openai/serving_chat.py +921 -0
  21. sglang/srt/entrypoints/openai/serving_completions.py +424 -0
  22. sglang/srt/entrypoints/openai/serving_embedding.py +169 -0
  23. sglang/srt/entrypoints/openai/serving_rerank.py +102 -0
  24. sglang/srt/entrypoints/openai/serving_score.py +61 -0
  25. sglang/srt/entrypoints/openai/usage_processor.py +81 -0
  26. sglang/srt/entrypoints/openai/utils.py +72 -0
  27. sglang/srt/function_call/base_format_detector.py +7 -4
  28. sglang/srt/function_call/deepseekv3_detector.py +1 -1
  29. sglang/srt/function_call/ebnf_composer.py +64 -10
  30. sglang/srt/function_call/function_call_parser.py +6 -6
  31. sglang/srt/function_call/llama32_detector.py +1 -1
  32. sglang/srt/function_call/mistral_detector.py +1 -1
  33. sglang/srt/function_call/pythonic_detector.py +1 -1
  34. sglang/srt/function_call/qwen25_detector.py +1 -1
  35. sglang/srt/{openai_api/utils.py → jinja_template_utils.py} +6 -5
  36. sglang/srt/layers/activation.py +21 -3
  37. sglang/srt/layers/attention/aiter_backend.py +5 -2
  38. sglang/srt/layers/attention/base_attn_backend.py +1 -1
  39. sglang/srt/layers/attention/cutlass_mla_backend.py +1 -0
  40. sglang/srt/layers/attention/flashattention_backend.py +19 -9
  41. sglang/srt/layers/attention/flashinfer_backend.py +9 -6
  42. sglang/srt/layers/attention/flashinfer_mla_backend.py +7 -4
  43. sglang/srt/layers/attention/flashmla_backend.py +5 -2
  44. sglang/srt/layers/attention/tbo_backend.py +3 -3
  45. sglang/srt/layers/attention/triton_backend.py +19 -11
  46. sglang/srt/layers/communicator.py +5 -5
  47. sglang/srt/layers/dp_attention.py +11 -2
  48. sglang/srt/layers/layernorm.py +29 -2
  49. sglang/srt/layers/logits_processor.py +2 -2
  50. sglang/srt/layers/moe/ep_moe/kernels.py +159 -2
  51. sglang/srt/layers/moe/ep_moe/layer.py +207 -1
  52. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_3_1/E=128,N=384,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128, 128].json +146 -0
  53. sglang/srt/layers/moe/fused_moe_triton/fused_moe.py +6 -0
  54. sglang/srt/layers/moe/fused_moe_triton/layer.py +75 -12
  55. sglang/srt/layers/moe/topk.py +91 -4
  56. sglang/srt/layers/quantization/compressed_tensors/compressed_tensors_moe.py +6 -2
  57. sglang/srt/layers/quantization/fp8.py +25 -17
  58. sglang/srt/layers/quantization/modelopt_quant.py +62 -8
  59. sglang/srt/layers/quantization/utils.py +5 -2
  60. sglang/srt/layers/rotary_embedding.py +42 -2
  61. sglang/srt/layers/sampler.py +1 -1
  62. sglang/srt/lora/lora_manager.py +173 -74
  63. sglang/srt/lora/mem_pool.py +49 -45
  64. sglang/srt/lora/utils.py +1 -1
  65. sglang/srt/managers/cache_controller.py +33 -15
  66. sglang/srt/managers/io_struct.py +9 -12
  67. sglang/srt/managers/schedule_batch.py +40 -31
  68. sglang/srt/managers/schedule_policy.py +70 -56
  69. sglang/srt/managers/scheduler.py +147 -62
  70. sglang/srt/managers/template_manager.py +226 -0
  71. sglang/srt/managers/tokenizer_manager.py +11 -8
  72. sglang/srt/managers/tp_worker.py +12 -2
  73. sglang/srt/managers/tp_worker_overlap_thread.py +11 -0
  74. sglang/srt/mem_cache/{paged_allocator.py → allocator.py} +125 -34
  75. sglang/srt/mem_cache/base_prefix_cache.py +52 -8
  76. sglang/srt/mem_cache/chunk_cache.py +11 -16
  77. sglang/srt/mem_cache/hiradix_cache.py +34 -23
  78. sglang/srt/mem_cache/memory_pool.py +118 -114
  79. sglang/srt/mem_cache/radix_cache.py +20 -16
  80. sglang/srt/model_executor/cuda_graph_runner.py +76 -45
  81. sglang/srt/model_executor/forward_batch_info.py +18 -5
  82. sglang/srt/model_executor/model_runner.py +22 -6
  83. sglang/srt/model_loader/loader.py +8 -1
  84. sglang/srt/model_loader/weight_utils.py +11 -2
  85. sglang/srt/models/deepseek_nextn.py +29 -27
  86. sglang/srt/models/deepseek_v2.py +108 -26
  87. sglang/srt/models/glm4.py +312 -0
  88. sglang/srt/models/mimo_mtp.py +2 -18
  89. sglang/srt/reasoning_parser.py +21 -11
  90. sglang/srt/server_args.py +36 -8
  91. sglang/srt/speculative/eagle_draft_cuda_graph_runner.py +131 -10
  92. sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py +125 -12
  93. sglang/srt/speculative/eagle_utils.py +80 -8
  94. sglang/srt/speculative/eagle_worker.py +124 -41
  95. sglang/srt/torch_memory_saver_adapter.py +19 -15
  96. sglang/srt/utils.py +177 -11
  97. sglang/test/test_block_fp8_ep.py +1 -0
  98. sglang/test/test_utils.py +1 -0
  99. sglang/version.py +1 -1
  100. {sglang-0.4.7.post1.dist-info → sglang-0.4.8.dist-info}/METADATA +4 -10
  101. {sglang-0.4.7.post1.dist-info → sglang-0.4.8.dist-info}/RECORD +104 -93
  102. sglang/srt/entrypoints/verl_engine.py +0 -179
  103. sglang/srt/openai_api/adapter.py +0 -2148
  104. {sglang-0.4.7.post1.dist-info → sglang-0.4.8.dist-info}/WHEEL +0 -0
  105. {sglang-0.4.7.post1.dist-info → sglang-0.4.8.dist-info}/licenses/LICENSE +0 -0
  106. {sglang-0.4.7.post1.dist-info → sglang-0.4.8.dist-info}/top_level.txt +0 -0
@@ -1,2148 +0,0 @@
1
- # Copyright 2023-2024 SGLang Team
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- # ==============================================================================
14
- """Conversion between OpenAI APIs and native SRT APIs"""
15
-
16
- import asyncio
17
- import base64
18
- import json
19
- import logging
20
- import os
21
- import time
22
- import uuid
23
- from http import HTTPStatus
24
- from typing import Dict, List
25
-
26
- from fastapi import HTTPException, Request, UploadFile
27
- from fastapi.responses import ORJSONResponse, StreamingResponse
28
- from pydantic import ValidationError
29
-
30
- from sglang.srt.code_completion_parser import (
31
- generate_completion_prompt_from_request,
32
- is_completion_template_defined,
33
- )
34
- from sglang.srt.conversation import (
35
- Conversation,
36
- SeparatorStyle,
37
- chat_template_exists,
38
- generate_chat_conv,
39
- generate_embedding_convs,
40
- get_conv_template_by_model_path,
41
- register_conv_template,
42
- )
43
- from sglang.srt.function_call.function_call_parser import FunctionCallParser
44
- from sglang.srt.managers.io_struct import (
45
- EmbeddingReqInput,
46
- GenerateReqInput,
47
- V1RerankReqInput,
48
- )
49
- from sglang.srt.openai_api.protocol import (
50
- BatchRequest,
51
- BatchResponse,
52
- ChatCompletionRequest,
53
- ChatCompletionResponse,
54
- ChatCompletionResponseChoice,
55
- ChatCompletionResponseStreamChoice,
56
- ChatCompletionStreamResponse,
57
- ChatCompletionTokenLogprob,
58
- ChatMessage,
59
- ChoiceLogprobs,
60
- CompletionRequest,
61
- CompletionResponse,
62
- CompletionResponseChoice,
63
- CompletionResponseStreamChoice,
64
- CompletionStreamResponse,
65
- DeltaMessage,
66
- EmbeddingObject,
67
- EmbeddingRequest,
68
- EmbeddingResponse,
69
- ErrorResponse,
70
- FileDeleteResponse,
71
- FileRequest,
72
- FileResponse,
73
- FunctionResponse,
74
- LogProbs,
75
- MultimodalEmbeddingInput,
76
- RerankResponse,
77
- ScoringRequest,
78
- ScoringResponse,
79
- ToolCall,
80
- TopLogprob,
81
- UsageInfo,
82
- )
83
- from sglang.srt.openai_api.utils import (
84
- detect_template_content_format,
85
- process_content_for_template_format,
86
- )
87
- from sglang.srt.reasoning_parser import ReasoningParser
88
- from sglang.utils import convert_json_schema_to_str, get_exception_traceback
89
-
90
- logger = logging.getLogger(__name__)
91
-
92
- chat_template_name = None
93
-
94
- # Global cache for template content format detection (one model/template per instance)
95
- # NOTE: A better approach would be to initialize the chat template format when the endpoint is created
96
- _cached_chat_template = None
97
- _cached_template_format = None
98
-
99
-
100
- class FileMetadata:
101
- def __init__(self, filename: str, purpose: str):
102
- self.filename = filename
103
- self.purpose = purpose
104
-
105
-
106
- # In-memory storage for batch jobs and files
107
- batch_storage: Dict[str, BatchResponse] = {}
108
- file_id_request: Dict[str, FileMetadata] = {}
109
- file_id_response: Dict[str, FileResponse] = {}
110
- # map file id to file path in SGLang backend
111
- file_id_storage: Dict[str, str] = {}
112
-
113
- # backend storage directory
114
- storage_dir = None
115
-
116
-
117
- def create_error_response(
118
- message: str,
119
- err_type: str = "BadRequestError",
120
- status_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
121
- ):
122
- error = ErrorResponse(message=message, type=err_type, code=status_code.value)
123
- return ORJSONResponse(content=error.model_dump(), status_code=error.code)
124
-
125
-
126
- def create_streaming_error_response(
127
- message: str,
128
- err_type: str = "BadRequestError",
129
- status_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
130
- ) -> str:
131
- error = ErrorResponse(message=message, type=err_type, code=status_code.value)
132
- json_str = json.dumps({"error": error.model_dump()})
133
- return json_str
134
-
135
-
136
- def load_chat_template_for_openai_api(tokenizer_manager, chat_template_arg, model_path):
137
- global chat_template_name
138
-
139
- logger.info(
140
- f"Use chat template for the OpenAI-compatible API server: {chat_template_arg}"
141
- )
142
-
143
- if not chat_template_exists(chat_template_arg):
144
- if not os.path.exists(chat_template_arg):
145
- raise RuntimeError(
146
- f"Chat template {chat_template_arg} is not a built-in template name "
147
- "or a valid chat template file path."
148
- )
149
- if chat_template_arg.endswith(".jinja"):
150
- with open(chat_template_arg, "r") as f:
151
- chat_template = "".join(f.readlines()).strip("\n")
152
- tokenizer_manager.tokenizer.chat_template = chat_template.replace(
153
- "\\n", "\n"
154
- )
155
- chat_template_name = None
156
- else:
157
- assert chat_template_arg.endswith(
158
- ".json"
159
- ), "unrecognized format of chat template file"
160
- with open(chat_template_arg, "r") as filep:
161
- template = json.load(filep)
162
- try:
163
- sep_style = SeparatorStyle[template["sep_style"]]
164
- except KeyError:
165
- raise ValueError(
166
- f"Unknown separator style: {template['sep_style']}"
167
- ) from None
168
- register_conv_template(
169
- Conversation(
170
- name=template["name"],
171
- system_template=template["system"] + "\n{system_message}",
172
- system_message=template.get("system_message", ""),
173
- roles=(template["user"], template["assistant"]),
174
- sep_style=sep_style,
175
- sep=template.get("sep", "\n"),
176
- stop_str=template["stop_str"],
177
- ),
178
- override=True,
179
- )
180
- chat_template_name = template["name"]
181
- else:
182
- chat_template_name = chat_template_arg
183
-
184
-
185
- def guess_chat_template_name_from_model_path(model_path):
186
- global chat_template_name
187
- chat_template_name = get_conv_template_by_model_path(model_path)
188
- if chat_template_name is not None:
189
- logger.info(
190
- f"Infer the chat template name from the model path and obtain the result: {chat_template_name}."
191
- )
192
-
193
-
194
- def _validate_prompt(prompt: str):
195
- """Validate that the prompt is not empty or whitespace only."""
196
- is_invalid = False
197
-
198
- # Check for empty/whitespace string
199
- if isinstance(prompt, str):
200
- is_invalid = not prompt.strip()
201
- # Check for various invalid list cases: [], [""], [" "], [[]]
202
- elif isinstance(prompt, list):
203
- is_invalid = not prompt or (
204
- len(prompt) == 1
205
- and (
206
- (isinstance(prompt[0], str) and not prompt[0].strip())
207
- or (isinstance(prompt[0], list) and not prompt[0])
208
- )
209
- )
210
-
211
- if is_invalid:
212
- raise HTTPException(
213
- status_code=400,
214
- detail="Input cannot be empty or contain only whitespace.",
215
- )
216
-
217
- return prompt
218
-
219
-
220
- async def v1_files_create(
221
- file: UploadFile, purpose: str, file_storage_path: str = None
222
- ):
223
- try:
224
- global storage_dir
225
- if file_storage_path:
226
- storage_dir = file_storage_path
227
- # Read the file content
228
- file_content = await file.read()
229
-
230
- # Create an instance of RequestBody
231
- request_body = FileRequest(file=file_content, purpose=purpose)
232
-
233
- # Save the file to the sglang_oai_storage directory
234
- os.makedirs(storage_dir, exist_ok=True)
235
- file_id = f"backend_input_file-{uuid.uuid4()}"
236
- filename = f"{file_id}.jsonl"
237
- file_path = os.path.join(storage_dir, filename)
238
-
239
- with open(file_path, "wb") as f:
240
- f.write(request_body.file)
241
-
242
- # add info to global file map
243
- file_id_request[file_id] = FileMetadata(filename=file.filename, purpose=purpose)
244
- file_id_storage[file_id] = file_path
245
-
246
- # Return the response in the required format
247
- response = FileResponse(
248
- id=file_id,
249
- bytes=len(request_body.file),
250
- created_at=int(time.time()),
251
- filename=file.filename,
252
- purpose=request_body.purpose,
253
- )
254
- file_id_response[file_id] = response
255
-
256
- return response
257
- except ValidationError as e:
258
- return {"error": "Invalid input", "details": e.errors()}
259
-
260
-
261
- async def v1_delete_file(file_id: str):
262
- # Retrieve the file job from the in-memory storage
263
- file_response = file_id_response.get(file_id)
264
- if file_response is None:
265
- raise HTTPException(status_code=404, detail="File not found")
266
- file_path = file_id_storage.get(file_id)
267
- if file_path is None:
268
- raise HTTPException(status_code=404, detail="File not found")
269
- os.remove(file_path)
270
- del file_id_response[file_id]
271
- del file_id_storage[file_id]
272
- return FileDeleteResponse(id=file_id, deleted=True)
273
-
274
-
275
- async def v1_batches(tokenizer_manager, raw_request: Request):
276
- try:
277
- body = await raw_request.json()
278
-
279
- batch_request = BatchRequest(**body)
280
-
281
- batch_id = f"batch_{uuid.uuid4()}"
282
-
283
- # Create an instance of BatchResponse
284
- batch_response = BatchResponse(
285
- id=batch_id,
286
- endpoint=batch_request.endpoint,
287
- input_file_id=batch_request.input_file_id,
288
- completion_window=batch_request.completion_window,
289
- created_at=int(time.time()),
290
- metadata=batch_request.metadata,
291
- )
292
-
293
- batch_storage[batch_id] = batch_response
294
-
295
- # Start processing the batch asynchronously
296
- asyncio.create_task(process_batch(tokenizer_manager, batch_id, batch_request))
297
-
298
- # Return the initial batch_response
299
- return batch_response
300
-
301
- except ValidationError as e:
302
- return {"error": "Invalid input", "details": e.errors()}
303
- except Exception as e:
304
- return {"error": str(e)}
305
-
306
-
307
- async def process_batch(tokenizer_manager, batch_id: str, batch_request: BatchRequest):
308
- try:
309
- # Update the batch status to "in_progress"
310
- batch_storage[batch_id].status = "in_progress"
311
- batch_storage[batch_id].in_progress_at = int(time.time())
312
-
313
- # Retrieve the input file content
314
- input_file_request = file_id_request.get(batch_request.input_file_id)
315
- if not input_file_request:
316
- raise ValueError("Input file not found")
317
-
318
- # Parse the JSONL file and process each request
319
- input_file_path = file_id_storage.get(batch_request.input_file_id)
320
- with open(input_file_path, "r", encoding="utf-8") as f:
321
- lines = f.readlines()
322
-
323
- total_requests = len(lines)
324
- completed_requests = 0
325
- failed_requests = 0
326
-
327
- all_ret = []
328
- end_point = batch_storage[batch_id].endpoint
329
- file_request_list = []
330
- all_requests = []
331
- request_ids = []
332
- for line_id, line in enumerate(lines):
333
- request_data = json.loads(line)
334
- file_request_list.append(request_data)
335
- body = request_data["body"]
336
- request_ids.append(f"{batch_id}-req_{line_id}")
337
-
338
- # Although streaming is supported for standalone completions, it is not supported in
339
- # batch mode (multiple completions in single request).
340
- if body.get("stream", False):
341
- raise ValueError("Streaming requests are not supported in batch mode")
342
-
343
- if end_point == "/v1/chat/completions":
344
- all_requests.append(ChatCompletionRequest(**body))
345
- elif end_point == "/v1/completions":
346
- all_requests.append(CompletionRequest(**body))
347
-
348
- if end_point == "/v1/chat/completions":
349
- adapted_request, request = v1_chat_generate_request(
350
- all_requests, tokenizer_manager, request_ids=request_ids
351
- )
352
- elif end_point == "/v1/completions":
353
- adapted_request, request = v1_generate_request(
354
- all_requests, request_ids=request_ids
355
- )
356
-
357
- try:
358
- created = int(time.time())
359
- ret = await tokenizer_manager.generate_request(adapted_request).__anext__()
360
- if not isinstance(ret, list):
361
- ret = [ret]
362
- if end_point == "/v1/chat/completions":
363
- responses = v1_chat_generate_response(
364
- request,
365
- ret,
366
- created,
367
- to_file=True,
368
- cache_report=tokenizer_manager.server_args.enable_cache_report,
369
- tool_call_parser=tokenizer_manager.server_args.tool_call_parser,
370
- )
371
- else:
372
- responses = v1_generate_response(
373
- request,
374
- ret,
375
- tokenizer_manager,
376
- created,
377
- to_file=True,
378
- cache_report=tokenizer_manager.server_args.enable_cache_report,
379
- )
380
-
381
- except Exception as e:
382
- logger.error(f"error: {get_exception_traceback()}")
383
- responses = []
384
- error_json = {
385
- "id": f"batch_req_{uuid.uuid4()}",
386
- "custom_id": request_data.get("custom_id"),
387
- "response": None,
388
- "error": {"message": str(e)},
389
- }
390
- all_ret.append(error_json)
391
- failed_requests += len(file_request_list)
392
-
393
- for idx, response in enumerate(responses):
394
- # the batch_req here can be changed to be named within a batch granularity
395
- response_json = {
396
- "id": f"batch_req_{uuid.uuid4()}",
397
- "custom_id": file_request_list[idx].get("custom_id"),
398
- "response": response,
399
- "error": None,
400
- }
401
- all_ret.append(response_json)
402
- completed_requests += 1
403
-
404
- # Write results to a new file
405
- output_file_id = f"backend_result_file-{uuid.uuid4()}"
406
- global storage_dir
407
- output_file_path = os.path.join(storage_dir, f"{output_file_id}.jsonl")
408
- with open(output_file_path, "w", encoding="utf-8") as f:
409
- for ret in all_ret:
410
- f.write(json.dumps(ret) + "\n")
411
-
412
- # Update batch response with output file information
413
- retrieve_batch = batch_storage[batch_id]
414
- retrieve_batch.output_file_id = output_file_id
415
- file_id_storage[output_file_id] = output_file_path
416
- file_id_response[output_file_id] = FileResponse(
417
- id=output_file_id,
418
- bytes=os.path.getsize(output_file_path),
419
- created_at=int(time.time()),
420
- filename=f"{output_file_id}.jsonl",
421
- purpose="batch_result",
422
- )
423
- # Update batch status to "completed"
424
- retrieve_batch.status = "completed"
425
- retrieve_batch.completed_at = int(time.time())
426
- retrieve_batch.request_counts = {
427
- "total": total_requests,
428
- "completed": completed_requests,
429
- "failed": failed_requests,
430
- }
431
-
432
- except Exception as e:
433
- logger.error(f"error: {e}")
434
- # Update batch status to "failed"
435
- retrieve_batch = batch_storage[batch_id]
436
- retrieve_batch.status = "failed"
437
- retrieve_batch.failed_at = int(time.time())
438
- retrieve_batch.errors = {"message": str(e)}
439
-
440
-
441
- async def v1_retrieve_batch(batch_id: str):
442
- # Retrieve the batch job from the in-memory storage
443
- batch_response = batch_storage.get(batch_id)
444
- if batch_response is None:
445
- raise HTTPException(status_code=404, detail="Batch not found")
446
-
447
- return batch_response
448
-
449
-
450
- async def v1_cancel_batch(tokenizer_manager, batch_id: str):
451
- # Retrieve the batch job from the in-memory storage
452
- batch_response = batch_storage.get(batch_id)
453
- if batch_response is None:
454
- raise HTTPException(status_code=404, detail="Batch not found")
455
-
456
- # Only do cancal when status is "validating" or "in_progress"
457
- if batch_response.status in ["validating", "in_progress"]:
458
- # Start cancelling the batch asynchronously
459
- asyncio.create_task(
460
- cancel_batch(
461
- tokenizer_manager=tokenizer_manager,
462
- batch_id=batch_id,
463
- input_file_id=batch_response.input_file_id,
464
- )
465
- )
466
-
467
- # Update batch status to "cancelling"
468
- batch_response.status = "cancelling"
469
-
470
- return batch_response
471
- else:
472
- raise HTTPException(
473
- status_code=500,
474
- detail=f"Current status is {batch_response.status}, no need to cancel",
475
- )
476
-
477
-
478
- async def cancel_batch(tokenizer_manager, batch_id: str, input_file_id: str):
479
- try:
480
- # Update the batch status to "cancelling"
481
- batch_storage[batch_id].status = "cancelling"
482
-
483
- # Retrieve the input file content
484
- input_file_request = file_id_request.get(input_file_id)
485
- if not input_file_request:
486
- raise ValueError("Input file not found")
487
-
488
- # Parse the JSONL file and process each request
489
- input_file_path = file_id_storage.get(input_file_id)
490
- with open(input_file_path, "r", encoding="utf-8") as f:
491
- lines = f.readlines()
492
-
493
- # Cancel requests by request_ids
494
- for line_id in range(len(lines)):
495
- rid = f"{batch_id}-req_{line_id}"
496
- tokenizer_manager.abort_request(rid=rid)
497
-
498
- retrieve_batch = batch_storage[batch_id]
499
- retrieve_batch.status = "cancelled"
500
-
501
- except Exception as e:
502
- logger.error("error in SGLang:", e)
503
- # Update batch status to "failed"
504
- retrieve_batch = batch_storage[batch_id]
505
- retrieve_batch.status = "failed"
506
- retrieve_batch.failed_at = int(time.time())
507
- retrieve_batch.errors = {"message": str(e)}
508
-
509
-
510
- async def v1_retrieve_file(file_id: str):
511
- # Retrieve the batch job from the in-memory storage
512
- file_response = file_id_response.get(file_id)
513
- if file_response is None:
514
- raise HTTPException(status_code=404, detail="File not found")
515
- return file_response
516
-
517
-
518
- async def v1_retrieve_file_content(file_id: str):
519
- file_pth = file_id_storage.get(file_id)
520
- if not file_pth or not os.path.exists(file_pth):
521
- raise HTTPException(status_code=404, detail="File not found")
522
-
523
- def iter_file():
524
- with open(file_pth, mode="rb") as file_like:
525
- yield from file_like
526
-
527
- return StreamingResponse(iter_file(), media_type="application/octet-stream")
528
-
529
-
530
- def v1_generate_request(
531
- all_requests: List[CompletionRequest], request_ids: List[str] = None
532
- ):
533
- if len(all_requests) > 1:
534
- first_prompt_type = type(all_requests[0].prompt)
535
- for request in all_requests:
536
- assert (
537
- type(request.prompt) is first_prompt_type
538
- ), "All prompts must be of the same type in file input settings"
539
- if request.n > 1:
540
- raise ValueError(
541
- "Parallel sampling is not supported for completions from files"
542
- )
543
-
544
- prompts = []
545
- sampling_params_list = []
546
- return_logprobs = []
547
- logprob_start_lens = []
548
- top_logprobs_nums = []
549
- lora_paths = []
550
- return_hidden_states = []
551
-
552
- for request in all_requests:
553
- # NOTE: with openai API, the prompt's logprobs are always not computed
554
- if request.echo and request.logprobs:
555
- logger.warning(
556
- "Echo is not compatible with logprobs. "
557
- "To compute logprobs of input prompt, please use the native /generate API."
558
- )
559
-
560
- prompt = request.prompt
561
- if is_completion_template_defined():
562
- prompt = generate_completion_prompt_from_request(request)
563
- prompts.append(prompt)
564
-
565
- lora_paths.append(request.lora_path)
566
- if request.echo and request.logprobs:
567
- current_logprob_start_len = 0
568
- else:
569
- current_logprob_start_len = -1
570
- sampling_params_list.append(
571
- {
572
- "temperature": request.temperature,
573
- "max_new_tokens": request.max_tokens,
574
- "min_new_tokens": request.min_tokens,
575
- "stop": request.stop,
576
- "stop_token_ids": request.stop_token_ids,
577
- "top_p": request.top_p,
578
- "top_k": request.top_k,
579
- "min_p": request.min_p,
580
- "presence_penalty": request.presence_penalty,
581
- "frequency_penalty": request.frequency_penalty,
582
- "repetition_penalty": request.repetition_penalty,
583
- "regex": request.regex,
584
- "json_schema": request.json_schema,
585
- "ebnf": request.ebnf,
586
- "n": request.n,
587
- "no_stop_trim": request.no_stop_trim,
588
- "ignore_eos": request.ignore_eos,
589
- "skip_special_tokens": request.skip_special_tokens,
590
- "logit_bias": request.logit_bias,
591
- }
592
- )
593
- return_logprobs.append(request.logprobs is not None)
594
- logprob_start_lens.append(current_logprob_start_len)
595
- top_logprobs_nums.append(
596
- request.logprobs if request.logprobs is not None else 0
597
- )
598
- return_hidden_states.append(request.return_hidden_states)
599
-
600
- if len(all_requests) == 1:
601
- if isinstance(prompts[0], str) or isinstance(prompts[0][0], str):
602
- prompt_kwargs = {"text": prompts[0]}
603
- else:
604
- prompt_kwargs = {"input_ids": prompts[0]}
605
- sampling_params_list = sampling_params_list[0]
606
- return_logprobs = return_logprobs[0]
607
- logprob_start_lens = logprob_start_lens[0]
608
- top_logprobs_nums = top_logprobs_nums[0]
609
- lora_paths = lora_paths[0]
610
- return_hidden_states = return_hidden_states[0]
611
- else:
612
- if isinstance(prompts[0], str) or isinstance(prompts[0][0], str):
613
- prompt_kwargs = {"text": prompts}
614
- else:
615
- prompt_kwargs = {"input_ids": prompts}
616
-
617
- adapted_request = GenerateReqInput(
618
- **prompt_kwargs,
619
- sampling_params=sampling_params_list,
620
- return_logprob=return_logprobs,
621
- top_logprobs_num=top_logprobs_nums,
622
- logprob_start_len=logprob_start_lens,
623
- return_text_in_logprobs=True,
624
- stream=all_requests[0].stream,
625
- rid=request_ids,
626
- lora_path=lora_paths,
627
- return_hidden_states=return_hidden_states,
628
- bootstrap_host=all_requests[0].bootstrap_host,
629
- bootstrap_port=all_requests[0].bootstrap_port,
630
- bootstrap_room=all_requests[0].bootstrap_room,
631
- )
632
-
633
- return adapted_request, all_requests if len(all_requests) > 1 else all_requests[0]
634
-
635
-
636
- def v1_generate_response(
637
- request, ret, tokenizer_manager, created, to_file=False, cache_report=False
638
- ):
639
- choices = []
640
- echo = False
641
-
642
- if (not isinstance(request, list)) and request.echo:
643
- # TODO: handle the case prompt is token ids
644
- if isinstance(request.prompt, list) and isinstance(request.prompt[0], str):
645
- # for the case of multiple str prompts
646
- prompts = request.prompt
647
- elif isinstance(request.prompt, list) and isinstance(request.prompt[0], list):
648
- # for the case of multiple token ids prompts
649
- prompts = [
650
- tokenizer_manager.tokenizer.decode(prompt, skip_special_tokens=True)
651
- for prompt in request.prompt
652
- ]
653
- elif isinstance(request.prompt, list) and isinstance(request.prompt[0], int):
654
- # for the case of single token ids prompt
655
- prompts = [
656
- tokenizer_manager.tokenizer.decode(
657
- request.prompt, skip_special_tokens=True
658
- )
659
- ]
660
- else:
661
- # for the case of single str prompt
662
- prompts = [request.prompt]
663
- echo = True
664
-
665
- for idx, ret_item in enumerate(ret):
666
- text = ret_item["text"]
667
- if isinstance(request, list) and request[idx].echo:
668
- echo = True
669
- text = request[idx].prompt + text
670
- if echo and not isinstance(request, list):
671
- prompt_index = idx // request.n
672
- text = prompts[prompt_index] + text
673
-
674
- logprobs = False
675
- if isinstance(request, list) and request[idx].logprobs is not None:
676
- logprobs = True
677
- elif (not isinstance(request, list)) and request.logprobs is not None:
678
- logprobs = True
679
- if logprobs:
680
- if echo:
681
- input_token_logprobs = ret_item["meta_info"]["input_token_logprobs"]
682
- input_top_logprobs = ret_item["meta_info"]["input_top_logprobs"]
683
- else:
684
- input_token_logprobs = None
685
- input_top_logprobs = None
686
-
687
- logprobs = to_openai_style_logprobs(
688
- input_token_logprobs=input_token_logprobs,
689
- input_top_logprobs=input_top_logprobs,
690
- output_token_logprobs=ret_item["meta_info"]["output_token_logprobs"],
691
- output_top_logprobs=ret_item["meta_info"]["output_top_logprobs"],
692
- )
693
- else:
694
- logprobs = None
695
-
696
- hidden_states = None
697
- if isinstance(request, list) and request[idx].return_hidden_states:
698
- hidden_states = ret_item["meta_info"].get("hidden_states", None)
699
- elif (not isinstance(request, list)) and request.return_hidden_states:
700
- hidden_states = ret_item["meta_info"].get("hidden_states", None)
701
- if hidden_states is not None:
702
- hidden_states = (
703
- hidden_states[-1] if hidden_states and len(hidden_states) > 1 else []
704
- )
705
-
706
- finish_reason = ret_item["meta_info"]["finish_reason"]
707
-
708
- if to_file:
709
- # to make the choice data json serializable
710
- choice_data = {
711
- "index": 0,
712
- "text": text,
713
- "logprobs": logprobs,
714
- "finish_reason": finish_reason["type"] if finish_reason else None,
715
- "matched_stop": (
716
- finish_reason["matched"]
717
- if finish_reason and "matched" in finish_reason
718
- else None
719
- ),
720
- }
721
- if hidden_states is not None:
722
- choice_data["hidden_states"] = hidden_states
723
- else:
724
- choice_data = CompletionResponseChoice(
725
- index=idx,
726
- text=text,
727
- logprobs=logprobs,
728
- finish_reason=finish_reason["type"] if finish_reason else None,
729
- matched_stop=(
730
- finish_reason["matched"]
731
- if finish_reason and "matched" in finish_reason
732
- else None
733
- ),
734
- hidden_states=hidden_states,
735
- )
736
-
737
- choices.append(choice_data)
738
-
739
- if to_file:
740
- responses = []
741
- for i, choice in enumerate(choices):
742
- response = {
743
- "status_code": 200,
744
- "request_id": ret[i]["meta_info"]["id"],
745
- "body": {
746
- # remain the same but if needed we can change that
747
- "id": ret[i]["meta_info"]["id"],
748
- "object": "text_completion",
749
- "created": created,
750
- "model": request[i].model,
751
- "choices": choice,
752
- "usage": {
753
- "prompt_tokens": ret[i]["meta_info"]["prompt_tokens"],
754
- "completion_tokens": ret[i]["meta_info"]["completion_tokens"],
755
- "total_tokens": ret[i]["meta_info"]["prompt_tokens"]
756
- + ret[i]["meta_info"]["completion_tokens"],
757
- },
758
- "system_fingerprint": None,
759
- },
760
- }
761
- responses.append(response)
762
- return responses
763
- else:
764
- prompt_tokens = sum(
765
- ret[i]["meta_info"]["prompt_tokens"] for i in range(0, len(ret), request.n)
766
- )
767
- completion_tokens = sum(item["meta_info"]["completion_tokens"] for item in ret)
768
- cached_tokens = sum(item["meta_info"].get("cached_tokens", 0) for item in ret)
769
- response = CompletionResponse(
770
- id=ret[0]["meta_info"]["id"],
771
- model=request.model,
772
- created=created,
773
- choices=choices,
774
- usage=UsageInfo(
775
- prompt_tokens=prompt_tokens,
776
- completion_tokens=completion_tokens,
777
- total_tokens=prompt_tokens + completion_tokens,
778
- prompt_tokens_details=(
779
- {"cached_tokens": cached_tokens} if cache_report else None
780
- ),
781
- ),
782
- )
783
- return response
784
-
785
-
786
- async def v1_completions(tokenizer_manager, raw_request: Request):
787
- try:
788
- request_json = await raw_request.json()
789
- except Exception as e:
790
- return create_error_response("Invalid request body, error: ", str(e))
791
- all_requests = [CompletionRequest(**request_json)]
792
- created = int(time.time())
793
- adapted_request, request = v1_generate_request(all_requests)
794
-
795
- if adapted_request.stream:
796
-
797
- async def generate_stream_resp():
798
- stream_buffers = {}
799
- n_prev_tokens = {}
800
- prompt_tokens = {}
801
- completion_tokens = {}
802
- cached_tokens = {}
803
- hidden_states = {}
804
-
805
- try:
806
- async for content in tokenizer_manager.generate_request(
807
- adapted_request, raw_request
808
- ):
809
- index = content.get("index", 0)
810
-
811
- stream_buffer = stream_buffers.get(index, "")
812
- n_prev_token = n_prev_tokens.get(index, 0)
813
-
814
- text = content["text"]
815
- prompt_tokens[index] = content["meta_info"]["prompt_tokens"]
816
- completion_tokens[index] = content["meta_info"]["completion_tokens"]
817
- cached_tokens[index] = content["meta_info"].get("cached_tokens", 0)
818
- hidden_states[index] = content["meta_info"].get(
819
- "hidden_states", None
820
- ) or hidden_states.get(index)
821
-
822
- if not stream_buffer: # The first chunk
823
- if request.echo:
824
- if isinstance(request.prompt, str):
825
- # for the case of single str prompts
826
- prompts = request.prompt
827
- elif isinstance(request.prompt, list):
828
- if isinstance(request.prompt[0], str):
829
- # for the case of multiple str prompts
830
- prompts = request.prompt[index // request.n]
831
- elif isinstance(request.prompt[0], int):
832
- # for the case of single token ids prompt
833
- prompts = tokenizer_manager.tokenizer.decode(
834
- request.prompt, skip_special_tokens=True
835
- )
836
- elif isinstance(request.prompt[0], list) and isinstance(
837
- request.prompt[0][0], int
838
- ):
839
- # for the case of multiple token ids prompts
840
- prompts = tokenizer_manager.tokenizer.decode(
841
- request.prompt[index // request.n],
842
- skip_special_tokens=True,
843
- )
844
-
845
- # Prepend prompt in response text.
846
- text = prompts + text
847
-
848
- if request.logprobs is not None:
849
- # The first chunk and echo is enabled.
850
- if not stream_buffer and request.echo:
851
- input_token_logprobs = content["meta_info"][
852
- "input_token_logprobs"
853
- ]
854
- input_top_logprobs = content["meta_info"][
855
- "input_top_logprobs"
856
- ]
857
- else:
858
- input_token_logprobs = None
859
- input_top_logprobs = None
860
-
861
- logprobs = to_openai_style_logprobs(
862
- input_token_logprobs=input_token_logprobs,
863
- input_top_logprobs=input_top_logprobs,
864
- output_token_logprobs=content["meta_info"][
865
- "output_token_logprobs"
866
- ][n_prev_token:],
867
- output_top_logprobs=content["meta_info"][
868
- "output_top_logprobs"
869
- ][n_prev_token:],
870
- )
871
- n_prev_token = len(
872
- content["meta_info"]["output_token_logprobs"]
873
- )
874
- else:
875
- logprobs = None
876
-
877
- delta = text[len(stream_buffer) :]
878
- stream_buffer = stream_buffer + delta
879
- finish_reason = content["meta_info"]["finish_reason"]
880
- choice_data = CompletionResponseStreamChoice(
881
- index=index,
882
- text=delta,
883
- logprobs=logprobs,
884
- finish_reason=finish_reason["type"] if finish_reason else None,
885
- matched_stop=(
886
- finish_reason["matched"]
887
- if finish_reason and "matched" in finish_reason
888
- else None
889
- ),
890
- )
891
- chunk = CompletionStreamResponse(
892
- id=content["meta_info"]["id"],
893
- created=created,
894
- object="text_completion",
895
- choices=[choice_data],
896
- model=request.model,
897
- )
898
-
899
- stream_buffers[index] = stream_buffer
900
- n_prev_tokens[index] = n_prev_token
901
-
902
- yield f"data: {chunk.model_dump_json()}\n\n"
903
- if request.return_hidden_states and hidden_states:
904
- for index, choice_hidden_states in hidden_states.items():
905
- last_token_hidden_states = (
906
- choice_hidden_states[-1]
907
- if choice_hidden_states and len(choice_hidden_states) > 1
908
- else []
909
- )
910
- hidden_states_chunk = CompletionStreamResponse(
911
- id=content["meta_info"]["id"],
912
- created=created,
913
- choices=[
914
- CompletionResponseStreamChoice(
915
- text="",
916
- index=index,
917
- hidden_states=last_token_hidden_states,
918
- finish_reason=None,
919
- )
920
- ],
921
- model=request.model,
922
- )
923
- yield f"data: {hidden_states_chunk.model_dump_json()}\n\n"
924
- if request.stream_options and request.stream_options.include_usage:
925
- total_prompt_tokens = sum(
926
- tokens
927
- for i, tokens in prompt_tokens.items()
928
- if i % request.n == 0
929
- )
930
- total_completion_tokens = sum(
931
- tokens for tokens in completion_tokens.values()
932
- )
933
- cache_report = tokenizer_manager.server_args.enable_cache_report
934
- if cache_report:
935
- cached_tokens_sum = sum(
936
- tokens for tokens in cached_tokens.values()
937
- )
938
- prompt_tokens_details = {"cached_tokens": cached_tokens_sum}
939
- else:
940
- prompt_tokens_details = None
941
- usage = UsageInfo(
942
- prompt_tokens=total_prompt_tokens,
943
- completion_tokens=total_completion_tokens,
944
- total_tokens=total_prompt_tokens + total_completion_tokens,
945
- prompt_tokens_details=prompt_tokens_details,
946
- )
947
-
948
- final_usage_chunk = CompletionStreamResponse(
949
- id=content["meta_info"]["id"],
950
- created=created,
951
- choices=[],
952
- model=request.model,
953
- usage=usage,
954
- )
955
- final_usage_data = final_usage_chunk.model_dump_json(
956
- exclude_none=True
957
- )
958
- yield f"data: {final_usage_data}\n\n"
959
- except ValueError as e:
960
- error = create_streaming_error_response(str(e))
961
- yield f"data: {error}\n\n"
962
- yield "data: [DONE]\n\n"
963
-
964
- return StreamingResponse(
965
- generate_stream_resp(),
966
- media_type="text/event-stream",
967
- background=tokenizer_manager.create_abort_task(adapted_request),
968
- )
969
-
970
- # Non-streaming response.
971
- try:
972
- ret = await tokenizer_manager.generate_request(
973
- adapted_request, raw_request
974
- ).__anext__()
975
- except ValueError as e:
976
- return create_error_response(str(e))
977
-
978
- if not isinstance(ret, list):
979
- ret = [ret]
980
-
981
- response = v1_generate_response(
982
- request,
983
- ret,
984
- tokenizer_manager,
985
- created,
986
- cache_report=tokenizer_manager.server_args.enable_cache_report,
987
- )
988
- return response
989
-
990
-
991
- def _get_enable_thinking_from_request(request_obj):
992
- """Extracts the 'enable_thinking' flag from request chat_template_kwargs.
993
-
994
- Args:
995
- request_obj: The request object (or an item from a list of requests).
996
-
997
- Returns:
998
- The boolean value of 'enable_thinking' if found and not True, otherwise True.
999
- """
1000
- if (
1001
- hasattr(request_obj, "chat_template_kwargs")
1002
- and request_obj.chat_template_kwargs
1003
- and request_obj.chat_template_kwargs.get("enable_thinking") is not None
1004
- ):
1005
- return request_obj.chat_template_kwargs.get("enable_thinking")
1006
- return True
1007
-
1008
-
1009
- def v1_chat_generate_request(
1010
- all_requests: List[ChatCompletionRequest],
1011
- tokenizer_manager,
1012
- request_ids: List[str] = None,
1013
- ):
1014
- input_ids = []
1015
- prompts = []
1016
- sampling_params_list = []
1017
- image_data_list = []
1018
- audio_data_list = []
1019
- return_logprobs = []
1020
- logprob_start_lens = []
1021
- top_logprobs_nums = []
1022
- modalities_list = []
1023
- lora_paths = []
1024
- return_hidden_states = []
1025
-
1026
- # NOTE: with openai API, the prompt's logprobs are always not computed
1027
-
1028
- is_multimodal = tokenizer_manager.model_config.is_multimodal
1029
- for request in all_requests:
1030
- # Prep the data needed for the underlying GenerateReqInput:
1031
- # - prompt: The full prompt string.
1032
- # - stop: Custom stop tokens.
1033
- # - image_data: None or a list of image strings (URLs or base64 strings).
1034
- # - audio_data: None or a list of audio strings (URLs).
1035
- # None skips any image processing in GenerateReqInput.
1036
- tool_call_constraint = None
1037
- prompt = ""
1038
- prompt_ids = []
1039
- if not isinstance(request.messages, str):
1040
- # Apply chat template and its stop strings.
1041
- tools = None
1042
- if request.tools and request.tool_choice != "none":
1043
- request.skip_special_tokens = False
1044
- if not isinstance(request.tool_choice, str):
1045
- tools = [
1046
- item.function.model_dump()
1047
- for item in request.tools
1048
- if item.function.name == request.tool_choice.function.name
1049
- ]
1050
- else:
1051
- tools = [item.function.model_dump() for item in request.tools]
1052
-
1053
- tool_call_parser = tokenizer_manager.server_args.tool_call_parser
1054
- parser = FunctionCallParser(request.tools, tool_call_parser)
1055
- tool_call_constraint = parser.get_structure_constraint(
1056
- request.tool_choice
1057
- )
1058
-
1059
- if chat_template_name is None:
1060
- openai_compatible_messages = []
1061
- image_data = []
1062
- audio_data = []
1063
- modalities = []
1064
-
1065
- # Detect template content format by analyzing the jinja template (cached globally)
1066
- global _cached_chat_template, _cached_template_format
1067
- current_template = tokenizer_manager.tokenizer.chat_template
1068
-
1069
- if current_template != _cached_chat_template:
1070
- # Template changed or first time - analyze it
1071
- _cached_chat_template = current_template
1072
- _cached_template_format = detect_template_content_format(
1073
- current_template
1074
- )
1075
- logger.info(
1076
- f"Detected chat template content format: {_cached_template_format}"
1077
- )
1078
-
1079
- template_content_format = _cached_template_format
1080
-
1081
- for message in request.messages:
1082
- if message.content is None:
1083
- message.content = ""
1084
- msg_dict = message.model_dump()
1085
-
1086
- # Process content based on detected template format
1087
- processed_msg = process_content_for_template_format(
1088
- msg_dict,
1089
- template_content_format,
1090
- image_data,
1091
- audio_data,
1092
- modalities,
1093
- )
1094
- openai_compatible_messages.append(processed_msg)
1095
-
1096
- # Handle assistant prefix for continue_final_message
1097
- if (
1098
- openai_compatible_messages
1099
- and openai_compatible_messages[-1]["role"] == "assistant"
1100
- ):
1101
- if request.continue_final_message:
1102
- # Remove the final assistant message so its content can be continued.
1103
- assistant_prefix = openai_compatible_messages[-1]["content"]
1104
- openai_compatible_messages = openai_compatible_messages[:-1]
1105
- else:
1106
- assistant_prefix = None
1107
- else:
1108
- assistant_prefix = None
1109
-
1110
- try:
1111
- prompt_ids = tokenizer_manager.tokenizer.apply_chat_template(
1112
- openai_compatible_messages,
1113
- tokenize=True,
1114
- add_generation_prompt=True,
1115
- tools=tools,
1116
- **(
1117
- request.chat_template_kwargs
1118
- if request.chat_template_kwargs
1119
- else {}
1120
- ),
1121
- )
1122
- except:
1123
- # This except branch will be triggered when the chosen model
1124
- # has a different tools input format that is not compatible
1125
- # with openAI's apply_chat_template tool_call format, like Mistral.
1126
- tools = [t if "function" in t else {"function": t} for t in tools]
1127
- prompt_ids = tokenizer_manager.tokenizer.apply_chat_template(
1128
- openai_compatible_messages,
1129
- tokenize=True,
1130
- add_generation_prompt=True,
1131
- tools=tools,
1132
- **(
1133
- request.chat_template_kwargs
1134
- if request.chat_template_kwargs
1135
- else {}
1136
- ),
1137
- )
1138
-
1139
- if assistant_prefix:
1140
- encoded = tokenizer_manager.tokenizer.encode(assistant_prefix)
1141
- if (
1142
- encoded
1143
- and encoded[0] == tokenizer_manager.tokenizer.bos_token_id
1144
- ):
1145
- encoded = encoded[1:]
1146
- prompt_ids += encoded
1147
- if is_multimodal:
1148
- prompt = tokenizer_manager.tokenizer.decode(prompt_ids)
1149
- stop = request.stop
1150
- image_data = image_data if image_data else None
1151
- audio_data = audio_data if audio_data else None
1152
- modalities = modalities if modalities else []
1153
- else:
1154
- conv = generate_chat_conv(request, chat_template_name)
1155
- # If we should continue the final assistant message, adjust the conversation.
1156
- if (
1157
- request.continue_final_message
1158
- and request.messages
1159
- and request.messages[-1].role == "assistant"
1160
- ):
1161
- # Remove the auto-added blank assistant turn, if present.
1162
- if conv.messages and conv.messages[-1][1] is None:
1163
- conv.messages.pop()
1164
- # Rebuild the prompt from the conversation.
1165
- prompt = conv.get_prompt()
1166
- # Strip any trailing stop tokens or separators that indicate end-of-assistant.
1167
- if isinstance(conv.stop_str, list):
1168
- for stop_token in conv.stop_str:
1169
- if prompt.endswith(stop_token):
1170
- prompt = prompt[: -len(stop_token)]
1171
- elif isinstance(conv.stop_str, str) and prompt.endswith(
1172
- conv.stop_str
1173
- ):
1174
- prompt = prompt[: -len(conv.stop_str)]
1175
- if conv.sep and prompt.endswith(conv.sep):
1176
- prompt = prompt[: -len(conv.sep)]
1177
- if getattr(conv, "sep2", None) and prompt.endswith(conv.sep2):
1178
- prompt = prompt[: -len(conv.sep2)]
1179
- else:
1180
- prompt = conv.get_prompt()
1181
-
1182
- image_data = conv.image_data
1183
- audio_data = conv.audio_data
1184
- modalities = conv.modalities
1185
- stop = conv.stop_str or [] if not request.ignore_eos else []
1186
-
1187
- if request.stop:
1188
- if isinstance(request.stop, str):
1189
- stop.append(request.stop)
1190
- else:
1191
- stop.extend(request.stop)
1192
-
1193
- if not is_multimodal:
1194
- prompt_ids = tokenizer_manager.tokenizer.encode(prompt)
1195
- else:
1196
- # Use the raw prompt and stop strings if the messages is already a string.
1197
- prompt_ids = request.messages
1198
- stop = request.stop
1199
- image_data = None
1200
- audio_data = None
1201
- modalities = []
1202
- prompt = request.messages
1203
- input_ids.append(prompt_ids)
1204
- return_logprobs.append(request.logprobs)
1205
- logprob_start_lens.append(-1)
1206
- top_logprobs_nums.append(request.top_logprobs or 0)
1207
- lora_paths.append(request.lora_path)
1208
- prompts.append(prompt)
1209
-
1210
- sampling_params = {
1211
- "temperature": request.temperature,
1212
- "max_new_tokens": request.max_tokens or request.max_completion_tokens,
1213
- "min_new_tokens": request.min_tokens,
1214
- "stop": stop,
1215
- "stop_token_ids": request.stop_token_ids,
1216
- "top_p": request.top_p,
1217
- "top_k": request.top_k,
1218
- "min_p": request.min_p,
1219
- "presence_penalty": request.presence_penalty,
1220
- "frequency_penalty": request.frequency_penalty,
1221
- "repetition_penalty": request.repetition_penalty,
1222
- "regex": request.regex,
1223
- "ebnf": request.ebnf,
1224
- "n": request.n,
1225
- "no_stop_trim": request.no_stop_trim,
1226
- "ignore_eos": request.ignore_eos,
1227
- "skip_special_tokens": request.skip_special_tokens,
1228
- "logit_bias": request.logit_bias,
1229
- }
1230
-
1231
- if request.response_format and request.response_format.type == "json_schema":
1232
- sampling_params["json_schema"] = convert_json_schema_to_str(
1233
- request.response_format.json_schema.schema_
1234
- )
1235
- elif request.response_format and request.response_format.type == "json_object":
1236
- sampling_params["json_schema"] = '{"type": "object"}'
1237
- elif (
1238
- request.response_format and request.response_format.type == "structural_tag"
1239
- ):
1240
- sampling_params["structural_tag"] = convert_json_schema_to_str(
1241
- request.response_format.model_dump(by_alias=True)
1242
- )
1243
-
1244
- # Check if there are already existing output constraints
1245
- has_existing_constraints = (
1246
- sampling_params.get("regex")
1247
- or sampling_params.get("ebnf")
1248
- or sampling_params.get("structural_tag")
1249
- or sampling_params.get("json_schema")
1250
- )
1251
-
1252
- if tool_call_constraint and has_existing_constraints:
1253
- logger.warning("Constrained decoding is not compatible with tool calls.")
1254
- elif tool_call_constraint:
1255
- constraint_type, constraint_value = tool_call_constraint
1256
- if constraint_type == "structural_tag":
1257
- sampling_params[constraint_type] = convert_json_schema_to_str(
1258
- constraint_value.model_dump(by_alias=True)
1259
- )
1260
- else:
1261
- sampling_params[constraint_type] = constraint_value
1262
-
1263
- sampling_params_list.append(sampling_params)
1264
-
1265
- image_data_list.append(image_data)
1266
- audio_data_list.append(audio_data)
1267
- modalities_list.append(modalities)
1268
- return_hidden_states.append(request.return_hidden_states)
1269
- if len(all_requests) == 1:
1270
- if is_multimodal:
1271
- # processor will need text input
1272
- prompt_kwargs = {"text": prompts[0]}
1273
- else:
1274
- if isinstance(input_ids[0], str):
1275
- prompt_kwargs = {"text": input_ids[0]}
1276
- else:
1277
- prompt_kwargs = {"input_ids": input_ids[0]}
1278
- sampling_params_list = sampling_params_list[0]
1279
- image_data_list = image_data_list[0]
1280
- audio_data_list = audio_data_list[0]
1281
- return_logprobs = return_logprobs[0]
1282
- logprob_start_lens = logprob_start_lens[0]
1283
- top_logprobs_nums = top_logprobs_nums[0]
1284
- modalities_list = modalities_list[0]
1285
- lora_paths = lora_paths[0]
1286
- request_ids = request_ids[0]
1287
- return_hidden_states = return_hidden_states[0]
1288
- else:
1289
- if tokenizer_manager.model_config.is_multimodal:
1290
- # processor will need text input
1291
- prompt_kwargs = {"text": prompts}
1292
- else:
1293
- if isinstance(input_ids[0], str):
1294
- prompt_kwargs = {"text": input_ids}
1295
- else:
1296
- prompt_kwargs = {"input_ids": input_ids}
1297
-
1298
- adapted_request = GenerateReqInput(
1299
- **prompt_kwargs,
1300
- image_data=image_data_list,
1301
- audio_data=audio_data_list,
1302
- sampling_params=sampling_params_list,
1303
- return_logprob=return_logprobs,
1304
- logprob_start_len=logprob_start_lens,
1305
- top_logprobs_num=top_logprobs_nums,
1306
- stream=all_requests[0].stream,
1307
- return_text_in_logprobs=True,
1308
- rid=request_ids,
1309
- modalities=modalities_list,
1310
- lora_path=lora_paths,
1311
- bootstrap_host=all_requests[0].bootstrap_host,
1312
- bootstrap_port=all_requests[0].bootstrap_port,
1313
- bootstrap_room=all_requests[0].bootstrap_room,
1314
- return_hidden_states=return_hidden_states,
1315
- )
1316
-
1317
- return adapted_request, all_requests if len(all_requests) > 1 else all_requests[0]
1318
-
1319
-
1320
- def v1_chat_generate_response(
1321
- request,
1322
- ret,
1323
- created,
1324
- to_file=False,
1325
- cache_report=False,
1326
- tool_call_parser=None,
1327
- reasoning_parser=None,
1328
- ):
1329
- choices = []
1330
-
1331
- for idx, ret_item in enumerate(ret):
1332
- logprobs = False
1333
- if isinstance(request, list) and request[idx].logprobs:
1334
- logprobs = True
1335
- elif (not isinstance(request, list)) and request.logprobs:
1336
- logprobs = True
1337
- if logprobs:
1338
- logprobs = to_openai_style_logprobs(
1339
- output_token_logprobs=ret_item["meta_info"]["output_token_logprobs"],
1340
- output_top_logprobs=ret_item["meta_info"].get(
1341
- "output_top_logprobs", None
1342
- ),
1343
- )
1344
- token_logprobs = []
1345
- for token_idx, (token, logprob) in enumerate(
1346
- zip(logprobs.tokens, logprobs.token_logprobs)
1347
- ):
1348
- token_bytes = list(token.encode("utf-8"))
1349
- top_logprobs = []
1350
- if logprobs.top_logprobs:
1351
- for top_token, top_logprob in logprobs.top_logprobs[
1352
- token_idx
1353
- ].items():
1354
- top_token_bytes = list(top_token.encode("utf-8"))
1355
- top_logprobs.append(
1356
- TopLogprob(
1357
- token=top_token,
1358
- bytes=top_token_bytes,
1359
- logprob=top_logprob,
1360
- )
1361
- )
1362
- token_logprobs.append(
1363
- ChatCompletionTokenLogprob(
1364
- token=token,
1365
- bytes=token_bytes,
1366
- logprob=logprob,
1367
- top_logprobs=top_logprobs,
1368
- )
1369
- )
1370
-
1371
- choice_logprobs = ChoiceLogprobs(content=token_logprobs)
1372
- else:
1373
- choice_logprobs = None
1374
-
1375
- if isinstance(request, list) and request[idx].return_hidden_states:
1376
- include_hidden_states = True
1377
- elif not isinstance(request, list) and request.return_hidden_states:
1378
- include_hidden_states = True
1379
- else:
1380
- include_hidden_states = False
1381
- if include_hidden_states and ret_item["meta_info"].get("hidden_states", None):
1382
- hidden_states = ret_item["meta_info"]["hidden_states"]
1383
- hidden_states = (
1384
- hidden_states[-1] if hidden_states and len(hidden_states) > 1 else []
1385
- )
1386
- else:
1387
- hidden_states = None
1388
-
1389
- finish_reason = ret_item["meta_info"]["finish_reason"]
1390
-
1391
- tool_calls = None
1392
- text = ret_item["text"]
1393
-
1394
- if isinstance(request, list):
1395
- tool_choice = request[idx].tool_choice
1396
- tools = request[idx].tools
1397
- separate_reasoning = request[idx].separate_reasoning
1398
- enable_thinking = _get_enable_thinking_from_request(request[idx])
1399
- else:
1400
- tool_choice = request.tool_choice
1401
- tools = request.tools
1402
- separate_reasoning = request.separate_reasoning
1403
- enable_thinking = _get_enable_thinking_from_request(request)
1404
-
1405
- reasoning_text = None
1406
- if reasoning_parser and separate_reasoning and enable_thinking:
1407
- try:
1408
- parser = ReasoningParser(
1409
- model_type=reasoning_parser, stream_reasoning=False
1410
- )
1411
- reasoning_text, text = parser.parse_non_stream(text)
1412
- except Exception as e:
1413
- logger.error(f"Exception: {e}")
1414
- return create_error_response(
1415
- HTTPStatus.BAD_REQUEST,
1416
- "Failed to parse reasoning related info to json format!",
1417
- )
1418
-
1419
- if tool_choice != "none" and tools:
1420
- parser = FunctionCallParser(tools, tool_call_parser)
1421
- if parser.has_tool_call(text):
1422
- if finish_reason["type"] == "stop":
1423
- finish_reason["type"] = "tool_calls"
1424
- finish_reason["matched"] = None
1425
- try:
1426
- text, call_info_list = parser.parse_non_stream(text)
1427
- tool_calls = [
1428
- ToolCall(
1429
- id=f"call_{base64.urlsafe_b64encode(uuid.uuid4().bytes).rstrip(b'=').decode()}",
1430
- function=FunctionResponse(
1431
- name=call_info.name, arguments=call_info.parameters
1432
- ),
1433
- )
1434
- for call_info in call_info_list
1435
- ]
1436
- except Exception as e:
1437
- logger.error(f"Exception: {e}")
1438
- return create_error_response(
1439
- HTTPStatus.BAD_REQUEST,
1440
- "Failed to parse fc related info to json format!",
1441
- )
1442
-
1443
- if to_file:
1444
- # to make the choice data json serializable
1445
- choice_data = {
1446
- "index": 0,
1447
- "message": {
1448
- "role": "assistant",
1449
- "content": text if text else None,
1450
- "tool_calls": tool_calls,
1451
- "reasoning_content": reasoning_text if reasoning_text else None,
1452
- },
1453
- "logprobs": choice_logprobs.model_dump() if choice_logprobs else None,
1454
- "finish_reason": finish_reason["type"] if finish_reason else None,
1455
- "matched_stop": (
1456
- finish_reason["matched"]
1457
- if finish_reason and "matched" in finish_reason
1458
- else None
1459
- ),
1460
- }
1461
- if hidden_states is not None:
1462
- choice_data["hidden_states"] = hidden_states
1463
- else:
1464
- choice_data = ChatCompletionResponseChoice(
1465
- index=idx,
1466
- message=ChatMessage(
1467
- role="assistant",
1468
- content=text if text else None,
1469
- tool_calls=tool_calls,
1470
- reasoning_content=reasoning_text if reasoning_text else None,
1471
- ),
1472
- logprobs=choice_logprobs,
1473
- finish_reason=finish_reason["type"] if finish_reason else None,
1474
- matched_stop=(
1475
- finish_reason["matched"]
1476
- if finish_reason and "matched" in finish_reason
1477
- else None
1478
- ),
1479
- hidden_states=hidden_states,
1480
- )
1481
-
1482
- choices.append(choice_data)
1483
-
1484
- if to_file:
1485
- responses = []
1486
-
1487
- for i, choice in enumerate(choices):
1488
- response = {
1489
- "status_code": 200,
1490
- "request_id": ret[i]["meta_info"]["id"],
1491
- "body": {
1492
- # remain the same but if needed we can change that
1493
- "id": ret[i]["meta_info"]["id"],
1494
- "object": "chat.completion",
1495
- "created": created,
1496
- "model": (
1497
- request[i].model if isinstance(request, list) else request.model
1498
- ),
1499
- "choices": choice,
1500
- "usage": {
1501
- "prompt_tokens": ret[i]["meta_info"]["prompt_tokens"],
1502
- "completion_tokens": ret[i]["meta_info"]["completion_tokens"],
1503
- "total_tokens": ret[i]["meta_info"]["prompt_tokens"]
1504
- + ret[i]["meta_info"]["completion_tokens"],
1505
- },
1506
- "system_fingerprint": None,
1507
- },
1508
- }
1509
- responses.append(response)
1510
- return responses
1511
- else:
1512
- prompt_tokens = sum(
1513
- ret[i]["meta_info"]["prompt_tokens"] for i in range(0, len(ret), request.n)
1514
- )
1515
- completion_tokens = sum(item["meta_info"]["completion_tokens"] for item in ret)
1516
- cached_tokens = sum(item["meta_info"].get("cached_tokens", 0) for item in ret)
1517
- response = ChatCompletionResponse(
1518
- id=ret[0]["meta_info"]["id"],
1519
- created=created,
1520
- model=request.model,
1521
- choices=choices,
1522
- usage=UsageInfo(
1523
- prompt_tokens=prompt_tokens,
1524
- completion_tokens=completion_tokens,
1525
- total_tokens=prompt_tokens + completion_tokens,
1526
- prompt_tokens_details=(
1527
- {"cached_tokens": cached_tokens} if cache_report else None
1528
- ),
1529
- ),
1530
- )
1531
- return response
1532
-
1533
-
1534
- async def v1_chat_completions(
1535
- tokenizer_manager, raw_request: Request, cache_report=False
1536
- ):
1537
- try:
1538
- request_json = await raw_request.json()
1539
- except Exception as e:
1540
- return create_error_response("Invalid request body, error: ", str(e))
1541
- all_requests = [ChatCompletionRequest(**request_json)]
1542
- created = int(time.time())
1543
- adapted_request, request = v1_chat_generate_request(
1544
- all_requests, tokenizer_manager, request_ids=[all_requests[0].rid]
1545
- )
1546
-
1547
- if adapted_request.stream:
1548
- parser_dict = {}
1549
- reasoning_parser_dict = {}
1550
-
1551
- async def generate_stream_resp():
1552
- tool_index_previous = -1
1553
- is_firsts = {}
1554
- stream_buffers = {}
1555
- n_prev_tokens = {}
1556
- prompt_tokens = {}
1557
- completion_tokens = {}
1558
- cached_tokens = {}
1559
- hidden_states = {}
1560
- try:
1561
- async for content in tokenizer_manager.generate_request(
1562
- adapted_request, raw_request
1563
- ):
1564
- index = content.get("index", 0)
1565
- text = content["text"]
1566
- hidden_states[index] = content["meta_info"].get(
1567
- "hidden_states", None
1568
- ) or hidden_states.get(index)
1569
-
1570
- is_first = is_firsts.get(index, True)
1571
- stream_buffer = stream_buffers.get(index, "")
1572
- n_prev_token = n_prev_tokens.get(index, 0)
1573
-
1574
- prompt_tokens[index] = content["meta_info"]["prompt_tokens"]
1575
- completion_tokens[index] = content["meta_info"]["completion_tokens"]
1576
- cached_tokens[index] = content["meta_info"].get("cached_tokens", 0)
1577
- if request.logprobs:
1578
- logprobs = to_openai_style_logprobs(
1579
- output_token_logprobs=content["meta_info"][
1580
- "output_token_logprobs"
1581
- ][n_prev_token:],
1582
- output_top_logprobs=content["meta_info"].get(
1583
- "output_top_logprobs", []
1584
- )[n_prev_token:],
1585
- )
1586
-
1587
- n_prev_token = len(
1588
- content["meta_info"]["output_token_logprobs"]
1589
- )
1590
- token_logprobs = []
1591
- for token, logprob in zip(
1592
- logprobs.tokens, logprobs.token_logprobs
1593
- ):
1594
- token_bytes = list(token.encode("utf-8"))
1595
- top_logprobs = []
1596
- if logprobs.top_logprobs:
1597
- for top_token, top_logprob in logprobs.top_logprobs[
1598
- 0
1599
- ].items():
1600
- top_token_bytes = list(top_token.encode("utf-8"))
1601
- top_logprobs.append(
1602
- TopLogprob(
1603
- token=top_token,
1604
- bytes=top_token_bytes,
1605
- logprob=top_logprob,
1606
- )
1607
- )
1608
- token_logprobs.append(
1609
- ChatCompletionTokenLogprob(
1610
- token=token,
1611
- bytes=token_bytes,
1612
- logprob=logprob,
1613
- top_logprobs=top_logprobs,
1614
- )
1615
- )
1616
-
1617
- choice_logprobs = ChoiceLogprobs(content=token_logprobs)
1618
-
1619
- else:
1620
- choice_logprobs = None
1621
-
1622
- finish_reason = content["meta_info"]["finish_reason"]
1623
- finish_reason_type = (
1624
- finish_reason["type"] if finish_reason else None
1625
- )
1626
-
1627
- if is_first:
1628
- # First chunk with role
1629
- is_first = False
1630
- delta = DeltaMessage(role="assistant")
1631
- choice_data = ChatCompletionResponseStreamChoice(
1632
- index=index,
1633
- delta=delta,
1634
- finish_reason=finish_reason_type,
1635
- matched_stop=(
1636
- finish_reason["matched"]
1637
- if finish_reason and "matched" in finish_reason
1638
- else None
1639
- ),
1640
- logprobs=choice_logprobs,
1641
- )
1642
- chunk = ChatCompletionStreamResponse(
1643
- id=content["meta_info"]["id"],
1644
- created=created,
1645
- choices=[choice_data],
1646
- model=request.model,
1647
- )
1648
- yield f"data: {chunk.model_dump_json()}\n\n"
1649
-
1650
- text = content["text"]
1651
- delta = text[len(stream_buffer) :]
1652
- new_stream_buffer = stream_buffer + delta
1653
-
1654
- enable_thinking = _get_enable_thinking_from_request(request)
1655
-
1656
- if (
1657
- tokenizer_manager.server_args.reasoning_parser
1658
- and request.separate_reasoning
1659
- and enable_thinking
1660
- ):
1661
- if index not in reasoning_parser_dict:
1662
- reasoning_parser_dict[index] = ReasoningParser(
1663
- tokenizer_manager.server_args.reasoning_parser,
1664
- request.stream_reasoning,
1665
- )
1666
- reasoning_parser = reasoning_parser_dict[index]
1667
- reasoning_text, delta = reasoning_parser.parse_stream_chunk(
1668
- delta
1669
- )
1670
- if reasoning_text:
1671
- choice_data = ChatCompletionResponseStreamChoice(
1672
- index=index,
1673
- delta=DeltaMessage(
1674
- reasoning_content=(
1675
- reasoning_text if reasoning_text else None
1676
- )
1677
- ),
1678
- finish_reason=finish_reason_type,
1679
- )
1680
- chunk = ChatCompletionStreamResponse(
1681
- id=content["meta_info"]["id"],
1682
- created=created,
1683
- choices=[choice_data],
1684
- model=request.model,
1685
- )
1686
- yield f"data: {chunk.model_dump_json()}\n\n"
1687
- if (delta and len(delta) == 0) or not delta:
1688
- stream_buffers[index] = new_stream_buffer
1689
- is_firsts[index] = is_first
1690
- n_prev_tokens[index] = n_prev_token
1691
- continue
1692
-
1693
- if request.tool_choice != "none" and request.tools:
1694
- if index not in parser_dict:
1695
- parser_dict[index] = FunctionCallParser(
1696
- tools=request.tools,
1697
- tool_call_parser=tokenizer_manager.server_args.tool_call_parser,
1698
- )
1699
- parser = parser_dict[index]
1700
-
1701
- # parse_increment => returns (normal_text, calls)
1702
- normal_text, calls = parser.parse_stream_chunk(delta)
1703
-
1704
- # 1) if there's normal_text, output it as normal content
1705
- if normal_text:
1706
- choice_data = ChatCompletionResponseStreamChoice(
1707
- index=index,
1708
- delta=DeltaMessage(
1709
- content=normal_text if normal_text else None
1710
- ),
1711
- finish_reason=finish_reason_type,
1712
- )
1713
- chunk = ChatCompletionStreamResponse(
1714
- id=content["meta_info"]["id"],
1715
- created=created,
1716
- choices=[choice_data],
1717
- model=request.model,
1718
- )
1719
- yield f"data: {chunk.model_dump_json()}\n\n"
1720
-
1721
- # 2) if we found calls, we output them as separate chunk(s)
1722
- for call_item in calls:
1723
- tool_index_current = call_item.tool_index
1724
- # transform call_item -> FunctionResponse + ToolCall
1725
- if finish_reason_type == "stop":
1726
- latest_delta_len = 0
1727
- if isinstance(call_item.parameters, str):
1728
- latest_delta_len = len(call_item.parameters)
1729
-
1730
- expected_call = json.dumps(
1731
- parser.detector.prev_tool_call_arr[index].get(
1732
- "arguments", {}
1733
- ),
1734
- ensure_ascii=False,
1735
- )
1736
- actual_call = parser.detector.streamed_args_for_tool[
1737
- index
1738
- ]
1739
- if latest_delta_len > 0:
1740
- actual_call = actual_call[:-latest_delta_len]
1741
- remaining_call = expected_call.replace(
1742
- actual_call, "", 1
1743
- )
1744
- call_item.parameters = remaining_call
1745
-
1746
- finish_reason_type = "tool_calls"
1747
- tool_call = ToolCall(
1748
- id=(
1749
- f"call_{base64.urlsafe_b64encode(uuid.uuid4().bytes).rstrip(b'=').decode()}"
1750
- if tool_index_previous != tool_index_current
1751
- else None
1752
- ),
1753
- index=call_item.tool_index,
1754
- function=FunctionResponse(
1755
- name=call_item.name,
1756
- arguments=call_item.parameters,
1757
- ),
1758
- )
1759
- tool_index_previous = tool_index_current
1760
- choice_data = ChatCompletionResponseStreamChoice(
1761
- index=index,
1762
- delta=DeltaMessage(tool_calls=[tool_call]),
1763
- finish_reason=(
1764
- None
1765
- if request.stream_options
1766
- and request.stream_options.include_usage
1767
- else finish_reason_type
1768
- ), # additional chunk will be return
1769
- )
1770
- chunk = ChatCompletionStreamResponse(
1771
- id=content["meta_info"]["id"],
1772
- created=created,
1773
- choices=[choice_data],
1774
- model=request.model,
1775
- )
1776
- yield f"data: {chunk.model_dump_json()}\n\n"
1777
-
1778
- stream_buffers[index] = new_stream_buffer
1779
- is_firsts[index] = is_first
1780
- n_prev_tokens[index] = n_prev_token
1781
-
1782
- else:
1783
- # No tool calls => just treat this as normal text
1784
- if delta or not (
1785
- request.stream_options
1786
- and request.stream_options.include_usage
1787
- ):
1788
- choice_data = ChatCompletionResponseStreamChoice(
1789
- index=index,
1790
- delta=DeltaMessage(content=delta if delta else None),
1791
- finish_reason=(
1792
- None
1793
- if request.stream_options
1794
- and request.stream_options.include_usage
1795
- else finish_reason_type
1796
- ),
1797
- matched_stop=(
1798
- finish_reason["matched"]
1799
- if finish_reason and "matched" in finish_reason
1800
- else None
1801
- ),
1802
- logprobs=choice_logprobs,
1803
- )
1804
- chunk = ChatCompletionStreamResponse(
1805
- id=content["meta_info"]["id"],
1806
- created=created,
1807
- choices=[choice_data],
1808
- model=request.model,
1809
- )
1810
- yield f"data: {chunk.model_dump_json()}\n\n"
1811
- stream_buffers[index] = new_stream_buffer
1812
- is_firsts[index] = is_first
1813
- n_prev_tokens[index] = n_prev_token
1814
- if finish_reason_type == "stop" and request.tool_choice != "none":
1815
- parser = FunctionCallParser(
1816
- tools=request.tools,
1817
- tool_call_parser=tokenizer_manager.server_args.tool_call_parser,
1818
- )
1819
- if parser.has_tool_call(new_stream_buffer):
1820
- # if the stream ends with empty string after tool calls
1821
- finish_reason_type = "tool_calls"
1822
-
1823
- if request.stream_options and request.stream_options.include_usage:
1824
- total_prompt_tokens = sum(
1825
- tokens
1826
- for i, tokens in prompt_tokens.items()
1827
- if i % request.n == 0
1828
- )
1829
- total_completion_tokens = sum(
1830
- tokens for tokens in completion_tokens.values()
1831
- )
1832
- cache_report = tokenizer_manager.server_args.enable_cache_report
1833
- if cache_report:
1834
- cached_tokens_sum = sum(
1835
- tokens for tokens in cached_tokens.values()
1836
- )
1837
- prompt_tokens_details = {"cached_tokens": cached_tokens_sum}
1838
- else:
1839
- prompt_tokens_details = None
1840
- usage = UsageInfo(
1841
- prompt_tokens=total_prompt_tokens,
1842
- completion_tokens=total_completion_tokens,
1843
- total_tokens=total_prompt_tokens + total_completion_tokens,
1844
- prompt_tokens_details=prompt_tokens_details,
1845
- )
1846
-
1847
- else:
1848
- usage = None
1849
- if request.return_hidden_states and hidden_states:
1850
- for index, choice_hidden_states in hidden_states.items():
1851
- last_token_hidden_states = (
1852
- choice_hidden_states[-1]
1853
- if choice_hidden_states and len(choice_hidden_states) > 1
1854
- else []
1855
- )
1856
- hidden_states_chunk = ChatCompletionStreamResponse(
1857
- id=content["meta_info"]["id"],
1858
- created=created,
1859
- choices=[
1860
- ChatCompletionResponseStreamChoice(
1861
- index=index,
1862
- delta=DeltaMessage(
1863
- hidden_states=last_token_hidden_states
1864
- ),
1865
- finish_reason=finish_reason_type,
1866
- )
1867
- ],
1868
- model=request.model,
1869
- )
1870
- yield f"data: {hidden_states_chunk.model_dump_json()}\n\n"
1871
- final_usage_chunk = ChatCompletionStreamResponse(
1872
- id=content["meta_info"]["id"],
1873
- created=created,
1874
- choices=[
1875
- ChatCompletionResponseStreamChoice(
1876
- index=index,
1877
- delta=DeltaMessage(),
1878
- finish_reason=finish_reason_type,
1879
- )
1880
- ],
1881
- model=request.model,
1882
- usage=usage,
1883
- )
1884
- yield f"data: {final_usage_chunk.model_dump_json()}\n\n"
1885
- except ValueError as e:
1886
- error = create_streaming_error_response(str(e))
1887
- yield f"data: {error}\n\n"
1888
- yield "data: [DONE]\n\n"
1889
-
1890
- return StreamingResponse(
1891
- generate_stream_resp(),
1892
- media_type="text/event-stream",
1893
- background=tokenizer_manager.create_abort_task(adapted_request),
1894
- )
1895
-
1896
- # Non-streaming response.
1897
- try:
1898
- ret = await tokenizer_manager.generate_request(
1899
- adapted_request, raw_request
1900
- ).__anext__()
1901
- except ValueError as e:
1902
- return create_error_response(str(e))
1903
- if not isinstance(ret, list):
1904
- ret = [ret]
1905
-
1906
- response = v1_chat_generate_response(
1907
- request,
1908
- ret,
1909
- created,
1910
- cache_report=tokenizer_manager.server_args.enable_cache_report,
1911
- tool_call_parser=tokenizer_manager.server_args.tool_call_parser,
1912
- reasoning_parser=tokenizer_manager.server_args.reasoning_parser,
1913
- )
1914
-
1915
- return response
1916
-
1917
-
1918
- def v1_embedding_request(all_requests, tokenizer_manager):
1919
- prompts = []
1920
- sampling_params_list = []
1921
- first_prompt_type = type(all_requests[0].input)
1922
-
1923
- for request in all_requests:
1924
- prompt = request.input
1925
- # Check for empty/whitespace string
1926
- prompt = _validate_prompt(request.input)
1927
- assert (
1928
- type(prompt) is first_prompt_type
1929
- ), "All prompts must be of the same type in file input settings"
1930
- prompts.append(prompt)
1931
-
1932
- if len(all_requests) == 1:
1933
- prompt = prompts[0]
1934
- if isinstance(prompt, str) or isinstance(prompt[0], str):
1935
- prompt_kwargs = {"text": prompt}
1936
- elif isinstance(prompt, list) and isinstance(
1937
- prompt[0], MultimodalEmbeddingInput
1938
- ):
1939
- texts = []
1940
- images = []
1941
- for item in prompt:
1942
- # TODO simply use padding for text, we should use a better way to handle this
1943
- texts.append(item.text if item.text is not None else "padding")
1944
- images.append(item.image if item.image is not None else None)
1945
- generate_prompts = []
1946
- if chat_template_name is not None:
1947
- convs = generate_embedding_convs(texts, images, chat_template_name)
1948
- for conv in convs:
1949
- generate_prompts.append(conv.get_prompt())
1950
- else:
1951
- generate_prompts = texts
1952
- if len(generate_prompts) == 1:
1953
- prompt_kwargs = {"text": generate_prompts[0], "image_data": images[0]}
1954
- else:
1955
- prompt_kwargs = {"text": generate_prompts, "image_data": images}
1956
- else:
1957
- prompt_kwargs = {"input_ids": prompt}
1958
- request_ids = all_requests[0].rid
1959
- else:
1960
- if isinstance(prompts[0], str) or isinstance(prompts[0][0], str):
1961
- prompt_kwargs = {"text": prompts}
1962
- elif isinstance(prompts[0], list) and isinstance(
1963
- prompts[0][0], MultimodalEmbeddingInput
1964
- ):
1965
- # TODO: multiple requests
1966
- raise NotImplementedError(
1967
- "Multiple requests with multimodal inputs are not supported yet"
1968
- )
1969
- else:
1970
- prompt_kwargs = {"input_ids": prompts}
1971
- request_ids = [req.rid for req in all_requests]
1972
-
1973
- adapted_request = EmbeddingReqInput(
1974
- rid=request_ids,
1975
- **prompt_kwargs,
1976
- )
1977
-
1978
- if len(all_requests) == 1:
1979
- return adapted_request, all_requests[0]
1980
- return adapted_request, all_requests
1981
-
1982
-
1983
- def v1_embedding_response(ret, model_path, to_file=False):
1984
- embedding_objects = []
1985
- prompt_tokens = 0
1986
- for idx, ret_item in enumerate(ret):
1987
- embedding_objects.append(
1988
- EmbeddingObject(
1989
- embedding=ret[idx]["embedding"],
1990
- index=idx,
1991
- )
1992
- )
1993
- prompt_tokens += ret[idx]["meta_info"]["prompt_tokens"]
1994
-
1995
- return EmbeddingResponse(
1996
- data=embedding_objects,
1997
- model=model_path,
1998
- usage=UsageInfo(
1999
- prompt_tokens=prompt_tokens,
2000
- total_tokens=prompt_tokens,
2001
- ),
2002
- )
2003
-
2004
-
2005
- async def v1_embeddings(tokenizer_manager, raw_request: Request):
2006
- try:
2007
- request_json = await raw_request.json()
2008
- except Exception as e:
2009
- return create_error_response("Invalid request body, error: ", str(e))
2010
- all_requests = [EmbeddingRequest(**request_json)]
2011
- adapted_request, request = v1_embedding_request(all_requests, tokenizer_manager)
2012
-
2013
- try:
2014
- ret = await tokenizer_manager.generate_request(
2015
- adapted_request, raw_request
2016
- ).__anext__()
2017
- except ValueError as e:
2018
- return create_error_response(str(e))
2019
-
2020
- if not isinstance(ret, list):
2021
- ret = [ret]
2022
-
2023
- response = v1_embedding_response(ret, tokenizer_manager.model_path)
2024
-
2025
- return response
2026
-
2027
-
2028
- def v1_rerank_request(obj: V1RerankReqInput):
2029
- if obj.query is None:
2030
- raise ValueError("query is required")
2031
- if obj.documents is None or len(obj.documents) == 0:
2032
- raise ValueError("documents is required")
2033
-
2034
- pairs = []
2035
- for doc in obj.documents:
2036
- pairs.append([obj.query, doc])
2037
-
2038
- adapted_request = EmbeddingReqInput(
2039
- text=pairs,
2040
- is_cross_encoder_request=True,
2041
- )
2042
-
2043
- return adapted_request
2044
-
2045
-
2046
- def v1_rerank_response(ret, obj: V1RerankReqInput):
2047
-
2048
- response = []
2049
- for idx, ret_item in enumerate(ret):
2050
- response.append(
2051
- RerankResponse(
2052
- score=ret[idx]["embedding"],
2053
- document=obj.documents[idx],
2054
- index=idx,
2055
- meta_info=ret[idx]["meta_info"],
2056
- )
2057
- )
2058
-
2059
- response.sort(key=lambda x: x.score, reverse=True)
2060
-
2061
- return response
2062
-
2063
-
2064
- async def v1_rerank(tokenizer_manager, obj: V1RerankReqInput, raw_request: Request):
2065
- adapted_request = v1_rerank_request(obj)
2066
-
2067
- try:
2068
- ret = await tokenizer_manager.generate_request(
2069
- adapted_request, raw_request
2070
- ).__anext__()
2071
-
2072
- except ValueError as e:
2073
- return create_error_response(str(e))
2074
-
2075
- if not isinstance(ret, list):
2076
- ret = [ret]
2077
-
2078
- response = v1_rerank_response(
2079
- ret,
2080
- obj,
2081
- )
2082
-
2083
- return response
2084
-
2085
-
2086
- def to_openai_style_logprobs(
2087
- input_token_logprobs=None,
2088
- output_token_logprobs=None,
2089
- input_top_logprobs=None,
2090
- output_top_logprobs=None,
2091
- ):
2092
- ret_logprobs = LogProbs()
2093
-
2094
- def append_token_logprobs(token_logprobs):
2095
- for logprob, _, token_text in token_logprobs:
2096
- ret_logprobs.tokens.append(token_text)
2097
- ret_logprobs.token_logprobs.append(logprob)
2098
-
2099
- # Not supported yet
2100
- ret_logprobs.text_offset.append(-1)
2101
-
2102
- def append_top_logprobs(top_logprobs):
2103
- for tokens in top_logprobs:
2104
- if tokens is not None:
2105
- ret_logprobs.top_logprobs.append(
2106
- {token[2]: token[0] for token in tokens}
2107
- )
2108
- else:
2109
- ret_logprobs.top_logprobs.append(None)
2110
-
2111
- if input_token_logprobs is not None:
2112
- append_token_logprobs(input_token_logprobs)
2113
- if output_token_logprobs is not None:
2114
- append_token_logprobs(output_token_logprobs)
2115
- if input_top_logprobs is not None:
2116
- append_top_logprobs(input_top_logprobs)
2117
- if output_top_logprobs is not None:
2118
- append_top_logprobs(output_top_logprobs)
2119
-
2120
- return ret_logprobs
2121
-
2122
-
2123
- async def v1_score(tokenizer_manager, raw_request):
2124
- try:
2125
- # Parse request
2126
- request_data = await raw_request.json()
2127
- request = ScoringRequest(**request_data)
2128
-
2129
- # Use tokenizer_manager's score_request method directly
2130
- scores = await tokenizer_manager.score_request(
2131
- query=request.query,
2132
- items=request.items,
2133
- label_token_ids=request.label_token_ids,
2134
- apply_softmax=request.apply_softmax,
2135
- item_first=request.item_first,
2136
- request=request,
2137
- )
2138
-
2139
- # Create response with just the scores, without usage info
2140
- response = ScoringResponse(
2141
- scores=scores,
2142
- model=request.model,
2143
- )
2144
- return response
2145
-
2146
- except Exception as e:
2147
- logger.error(f"Error in v1_score: {str(e)}")
2148
- return create_error_response(str(e))