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