sglang 0.4.1.post6__py3-none-any.whl → 0.4.2__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 (141) hide show
  1. sglang/__init__.py +21 -23
  2. sglang/api.py +2 -7
  3. sglang/bench_offline_throughput.py +41 -27
  4. sglang/bench_one_batch.py +60 -4
  5. sglang/bench_one_batch_server.py +1 -1
  6. sglang/bench_serving.py +83 -71
  7. sglang/lang/backend/runtime_endpoint.py +183 -4
  8. sglang/lang/chat_template.py +46 -4
  9. sglang/launch_server.py +1 -1
  10. sglang/srt/_custom_ops.py +80 -42
  11. sglang/srt/configs/device_config.py +1 -1
  12. sglang/srt/configs/load_config.py +1 -0
  13. sglang/srt/configs/model_config.py +1 -0
  14. sglang/srt/constrained/base_grammar_backend.py +21 -0
  15. sglang/srt/constrained/xgrammar_backend.py +8 -4
  16. sglang/srt/conversation.py +14 -1
  17. sglang/srt/distributed/__init__.py +3 -3
  18. sglang/srt/distributed/communication_op.py +2 -1
  19. sglang/srt/distributed/device_communicators/cuda_wrapper.py +2 -1
  20. sglang/srt/distributed/device_communicators/custom_all_reduce.py +112 -42
  21. sglang/srt/distributed/device_communicators/custom_all_reduce_utils.py +2 -2
  22. sglang/srt/distributed/device_communicators/hpu_communicator.py +2 -1
  23. sglang/srt/distributed/device_communicators/pynccl.py +80 -1
  24. sglang/srt/distributed/device_communicators/pynccl_wrapper.py +112 -2
  25. sglang/srt/distributed/device_communicators/shm_broadcast.py +5 -72
  26. sglang/srt/distributed/device_communicators/xpu_communicator.py +2 -1
  27. sglang/srt/distributed/parallel_state.py +1 -1
  28. sglang/srt/distributed/utils.py +2 -1
  29. sglang/srt/entrypoints/engine.py +452 -0
  30. sglang/srt/entrypoints/http_server.py +603 -0
  31. sglang/srt/function_call_parser.py +494 -0
  32. sglang/srt/layers/activation.py +8 -8
  33. sglang/srt/layers/attention/flashinfer_backend.py +10 -9
  34. sglang/srt/layers/attention/triton_backend.py +4 -6
  35. sglang/srt/layers/attention/vision.py +204 -0
  36. sglang/srt/layers/dp_attention.py +71 -0
  37. sglang/srt/layers/layernorm.py +5 -5
  38. sglang/srt/layers/linear.py +65 -14
  39. sglang/srt/layers/logits_processor.py +49 -64
  40. sglang/srt/layers/moe/ep_moe/layer.py +24 -16
  41. sglang/srt/layers/moe/fused_moe_native.py +84 -1
  42. sglang/srt/layers/moe/fused_moe_triton/configs/E=256,N=256,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  43. sglang/srt/layers/moe/fused_moe_triton/fused_moe.py +27 -7
  44. sglang/srt/layers/moe/fused_moe_triton/layer.py +38 -5
  45. sglang/srt/layers/parameter.py +18 -8
  46. sglang/srt/layers/quantization/__init__.py +20 -23
  47. sglang/srt/layers/quantization/configs/N=1536,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  48. sglang/srt/layers/quantization/configs/N=3072,K=1536,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  49. sglang/srt/layers/quantization/configs/N=4096,K=512,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  50. sglang/srt/layers/quantization/configs/N=4608,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  51. sglang/srt/layers/quantization/configs/N=512,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  52. sglang/srt/layers/quantization/configs/N=576,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  53. sglang/srt/layers/quantization/configs/N=7168,K=2048,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  54. sglang/srt/layers/quantization/configs/N=7168,K=2304,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  55. sglang/srt/layers/quantization/configs/N=7168,K=256,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128, 128].json +164 -0
  56. sglang/srt/layers/quantization/fp8.py +10 -4
  57. sglang/srt/layers/quantization/modelopt_quant.py +1 -2
  58. sglang/srt/layers/quantization/w8a8_int8.py +1 -1
  59. sglang/srt/layers/radix_attention.py +2 -2
  60. sglang/srt/layers/rotary_embedding.py +1184 -31
  61. sglang/srt/layers/sampler.py +64 -6
  62. sglang/srt/layers/torchao_utils.py +12 -6
  63. sglang/srt/layers/vocab_parallel_embedding.py +2 -2
  64. sglang/srt/lora/lora.py +1 -9
  65. sglang/srt/managers/configure_logging.py +3 -0
  66. sglang/srt/managers/data_parallel_controller.py +79 -72
  67. sglang/srt/managers/detokenizer_manager.py +24 -6
  68. sglang/srt/managers/image_processor.py +158 -2
  69. sglang/srt/managers/io_struct.py +57 -3
  70. sglang/srt/managers/schedule_batch.py +78 -45
  71. sglang/srt/managers/schedule_policy.py +26 -12
  72. sglang/srt/managers/scheduler.py +326 -201
  73. sglang/srt/managers/session_controller.py +1 -0
  74. sglang/srt/managers/tokenizer_manager.py +210 -121
  75. sglang/srt/managers/tp_worker.py +6 -4
  76. sglang/srt/managers/tp_worker_overlap_thread.py +5 -8
  77. sglang/srt/managers/utils.py +44 -0
  78. sglang/srt/mem_cache/memory_pool.py +10 -32
  79. sglang/srt/metrics/collector.py +15 -6
  80. sglang/srt/model_executor/cuda_graph_runner.py +26 -30
  81. sglang/srt/model_executor/forward_batch_info.py +5 -7
  82. sglang/srt/model_executor/model_runner.py +44 -19
  83. sglang/srt/model_loader/loader.py +83 -6
  84. sglang/srt/model_loader/weight_utils.py +145 -6
  85. sglang/srt/models/baichuan.py +6 -6
  86. sglang/srt/models/chatglm.py +2 -2
  87. sglang/srt/models/commandr.py +17 -5
  88. sglang/srt/models/dbrx.py +13 -5
  89. sglang/srt/models/deepseek.py +3 -3
  90. sglang/srt/models/deepseek_v2.py +11 -11
  91. sglang/srt/models/exaone.py +2 -2
  92. sglang/srt/models/gemma.py +2 -2
  93. sglang/srt/models/gemma2.py +15 -25
  94. sglang/srt/models/gpt2.py +3 -5
  95. sglang/srt/models/gpt_bigcode.py +1 -1
  96. sglang/srt/models/granite.py +2 -2
  97. sglang/srt/models/grok.py +4 -3
  98. sglang/srt/models/internlm2.py +2 -2
  99. sglang/srt/models/llama.py +7 -5
  100. sglang/srt/models/minicpm.py +2 -2
  101. sglang/srt/models/minicpm3.py +9 -9
  102. sglang/srt/models/minicpmv.py +1238 -0
  103. sglang/srt/models/mixtral.py +3 -3
  104. sglang/srt/models/mixtral_quant.py +3 -3
  105. sglang/srt/models/mllama.py +2 -2
  106. sglang/srt/models/olmo.py +3 -3
  107. sglang/srt/models/olmo2.py +4 -4
  108. sglang/srt/models/olmoe.py +7 -13
  109. sglang/srt/models/phi3_small.py +2 -2
  110. sglang/srt/models/qwen.py +2 -2
  111. sglang/srt/models/qwen2.py +41 -4
  112. sglang/srt/models/qwen2_moe.py +3 -3
  113. sglang/srt/models/qwen2_vl.py +22 -122
  114. sglang/srt/models/stablelm.py +2 -2
  115. sglang/srt/models/torch_native_llama.py +20 -7
  116. sglang/srt/models/xverse.py +6 -6
  117. sglang/srt/models/xverse_moe.py +6 -6
  118. sglang/srt/openai_api/adapter.py +139 -37
  119. sglang/srt/openai_api/protocol.py +7 -4
  120. sglang/srt/sampling/custom_logit_processor.py +38 -0
  121. sglang/srt/sampling/penaltylib/penalizers/repetition_penalty.py +11 -14
  122. sglang/srt/sampling/sampling_batch_info.py +143 -18
  123. sglang/srt/sampling/sampling_params.py +3 -1
  124. sglang/srt/server.py +4 -1090
  125. sglang/srt/server_args.py +77 -15
  126. sglang/srt/speculative/eagle_utils.py +37 -15
  127. sglang/srt/speculative/eagle_worker.py +11 -13
  128. sglang/srt/utils.py +164 -129
  129. sglang/test/runners.py +8 -13
  130. sglang/test/test_programs.py +2 -1
  131. sglang/test/test_utils.py +83 -22
  132. sglang/utils.py +12 -2
  133. sglang/version.py +1 -1
  134. {sglang-0.4.1.post6.dist-info → sglang-0.4.2.dist-info}/METADATA +21 -10
  135. {sglang-0.4.1.post6.dist-info → sglang-0.4.2.dist-info}/RECORD +138 -123
  136. sglang/launch_server_llavavid.py +0 -25
  137. sglang/srt/constrained/__init__.py +0 -16
  138. sglang/srt/distributed/device_communicators/__init__.py +0 -0
  139. {sglang-0.4.1.post6.dist-info → sglang-0.4.2.dist-info}/LICENSE +0 -0
  140. {sglang-0.4.1.post6.dist-info → sglang-0.4.2.dist-info}/WHEEL +0 -0
  141. {sglang-0.4.1.post6.dist-info → sglang-0.4.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,603 @@
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
+ """
15
+ The entry point of inference server. (SRT = SGLang Runtime)
16
+
17
+ This file implements HTTP APIs for the inferenc engine via fastapi.
18
+ """
19
+
20
+ import asyncio
21
+ import dataclasses
22
+ import logging
23
+ import multiprocessing as multiprocessing
24
+ import os
25
+ import threading
26
+ import time
27
+ from http import HTTPStatus
28
+ from typing import AsyncIterator, Dict, Optional
29
+
30
+ # Fix a bug of Python threading
31
+ setattr(threading, "_register_atexit", lambda *args, **kwargs: None)
32
+
33
+ import orjson
34
+ import requests
35
+ import uvicorn
36
+ import uvloop
37
+ from fastapi import FastAPI, File, Form, Request, UploadFile
38
+ from fastapi.middleware.cors import CORSMiddleware
39
+ from fastapi.responses import ORJSONResponse, Response, StreamingResponse
40
+
41
+ from sglang.srt.entrypoints.engine import _launch_subprocesses
42
+ from sglang.srt.function_call_parser import FunctionCallParser
43
+ from sglang.srt.managers.io_struct import (
44
+ CloseSessionReqInput,
45
+ ConfigureLoggingReq,
46
+ EmbeddingReqInput,
47
+ FunctionCallReqInput,
48
+ GenerateReqInput,
49
+ GetWeightsByNameReqInput,
50
+ InitWeightsUpdateGroupReqInput,
51
+ OpenSessionReqInput,
52
+ ReleaseMemoryOccupationReqInput,
53
+ ResumeMemoryOccupationReqInput,
54
+ UpdateWeightFromDiskReqInput,
55
+ UpdateWeightsFromDistributedReqInput,
56
+ )
57
+ from sglang.srt.managers.tokenizer_manager import TokenizerManager
58
+ from sglang.srt.metrics.func_timer import enable_func_timer
59
+ from sglang.srt.openai_api.adapter import (
60
+ v1_batches,
61
+ v1_cancel_batch,
62
+ v1_chat_completions,
63
+ v1_completions,
64
+ v1_delete_file,
65
+ v1_embeddings,
66
+ v1_files_create,
67
+ v1_retrieve_batch,
68
+ v1_retrieve_file,
69
+ v1_retrieve_file_content,
70
+ )
71
+ from sglang.srt.openai_api.protocol import ModelCard, ModelList
72
+ from sglang.srt.server_args import ServerArgs
73
+ from sglang.srt.utils import (
74
+ add_api_key_middleware,
75
+ add_prometheus_middleware,
76
+ delete_directory,
77
+ kill_process_tree,
78
+ set_uvicorn_logging_configs,
79
+ )
80
+ from sglang.utils import get_exception_traceback
81
+ from sglang.version import __version__
82
+
83
+ logger = logging.getLogger(__name__)
84
+ asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
85
+
86
+ # Fast API
87
+ app = FastAPI()
88
+ app.add_middleware(
89
+ CORSMiddleware,
90
+ allow_origins=["*"],
91
+ allow_credentials=True,
92
+ allow_methods=["*"],
93
+ allow_headers=["*"],
94
+ )
95
+
96
+
97
+ # Store global states
98
+ @dataclasses.dataclass
99
+ class _GlobalState:
100
+ tokenizer_manager: TokenizerManager
101
+ scheduler_info: Dict
102
+
103
+
104
+ _global_state: Optional[_GlobalState] = None
105
+
106
+
107
+ def set_global_state(global_state: _GlobalState):
108
+ global _global_state
109
+ _global_state = global_state
110
+
111
+
112
+ ##### Native API endpoints #####
113
+
114
+
115
+ @app.get("/health")
116
+ async def health() -> Response:
117
+ """Check the health of the http server."""
118
+ return Response(status_code=200)
119
+
120
+
121
+ @app.get("/health_generate")
122
+ async def health_generate(request: Request) -> Response:
123
+ """Check the health of the inference server by generating one token."""
124
+
125
+ sampling_params = {"max_new_tokens": 1, "temperature": 0.7}
126
+
127
+ if _global_state.tokenizer_manager.is_generation:
128
+ gri = GenerateReqInput(
129
+ input_ids=[0], sampling_params=sampling_params, log_metrics=False
130
+ )
131
+ else:
132
+ gri = EmbeddingReqInput(
133
+ input_ids=[0], sampling_params=sampling_params, log_metrics=False
134
+ )
135
+
136
+ try:
137
+ async for _ in _global_state.tokenizer_manager.generate_request(gri, request):
138
+ break
139
+ return Response(status_code=200)
140
+ except Exception as e:
141
+ logger.exception(e)
142
+ return Response(status_code=503)
143
+
144
+
145
+ @app.get("/get_model_info")
146
+ async def get_model_info():
147
+ """Get the model information."""
148
+ result = {
149
+ "model_path": _global_state.tokenizer_manager.model_path,
150
+ "tokenizer_path": _global_state.tokenizer_manager.server_args.tokenizer_path,
151
+ "is_generation": _global_state.tokenizer_manager.is_generation,
152
+ }
153
+ return result
154
+
155
+
156
+ @app.get("/get_server_info")
157
+ async def get_server_info():
158
+ return {
159
+ **dataclasses.asdict(_global_state.tokenizer_manager.server_args),
160
+ **_global_state.scheduler_info,
161
+ "version": __version__,
162
+ }
163
+
164
+
165
+ # fastapi implicitly converts json in the request to obj (dataclass)
166
+ @app.api_route("/generate", methods=["POST", "PUT"])
167
+ async def generate_request(obj: GenerateReqInput, request: Request):
168
+ """Handle a generate request."""
169
+ if obj.stream:
170
+
171
+ async def stream_results() -> AsyncIterator[bytes]:
172
+ try:
173
+ async for out in _global_state.tokenizer_manager.generate_request(
174
+ obj, request
175
+ ):
176
+ yield b"data: " + orjson.dumps(
177
+ out, option=orjson.OPT_NON_STR_KEYS
178
+ ) + b"\n\n"
179
+ except ValueError as e:
180
+ out = {"error": {"message": str(e)}}
181
+ yield b"data: " + orjson.dumps(
182
+ out, option=orjson.OPT_NON_STR_KEYS
183
+ ) + b"\n\n"
184
+ yield b"data: [DONE]\n\n"
185
+
186
+ return StreamingResponse(
187
+ stream_results(),
188
+ media_type="text/event-stream",
189
+ background=_global_state.tokenizer_manager.create_abort_task(obj),
190
+ )
191
+ else:
192
+ try:
193
+ ret = await _global_state.tokenizer_manager.generate_request(
194
+ obj, request
195
+ ).__anext__()
196
+ return ret
197
+ except ValueError as e:
198
+ logger.error(f"Error: {e}")
199
+ return _create_error_response(e)
200
+
201
+
202
+ @app.api_route("/encode", methods=["POST", "PUT"])
203
+ async def encode_request(obj: EmbeddingReqInput, request: Request):
204
+ """Handle an embedding request."""
205
+ try:
206
+ ret = await _global_state.tokenizer_manager.generate_request(
207
+ obj, request
208
+ ).__anext__()
209
+ return ret
210
+ except ValueError as e:
211
+ return _create_error_response(e)
212
+
213
+
214
+ @app.api_route("/classify", methods=["POST", "PUT"])
215
+ async def classify_request(obj: EmbeddingReqInput, request: Request):
216
+ """Handle a reward model request. Now the arguments and return values are the same as embedding models."""
217
+ try:
218
+ ret = await _global_state.tokenizer_manager.generate_request(
219
+ obj, request
220
+ ).__anext__()
221
+ return ret
222
+ except ValueError as e:
223
+ return _create_error_response(e)
224
+
225
+
226
+ @app.post("/flush_cache")
227
+ async def flush_cache():
228
+ """Flush the radix cache."""
229
+ _global_state.tokenizer_manager.flush_cache()
230
+ return Response(
231
+ content="Cache flushed.\nPlease check backend logs for more details. "
232
+ "(When there are running or waiting requests, the operation will not be performed.)\n",
233
+ status_code=200,
234
+ )
235
+
236
+
237
+ @app.api_route("/start_profile", methods=["GET", "POST"])
238
+ async def start_profile_async():
239
+ """Start profiling."""
240
+ _global_state.tokenizer_manager.start_profile()
241
+ return Response(
242
+ content="Start profiling.\n",
243
+ status_code=200,
244
+ )
245
+
246
+
247
+ @app.api_route("/stop_profile", methods=["GET", "POST"])
248
+ async def stop_profile_async():
249
+ """Stop profiling."""
250
+ _global_state.tokenizer_manager.stop_profile()
251
+ return Response(
252
+ content="Stop profiling. This will take some time.\n",
253
+ status_code=200,
254
+ )
255
+
256
+
257
+ @app.post("/update_weights_from_disk")
258
+ async def update_weights_from_disk(obj: UpdateWeightFromDiskReqInput, request: Request):
259
+ """Update the weights from disk in-place without re-launching the server."""
260
+ success, message = await _global_state.tokenizer_manager.update_weights_from_disk(
261
+ obj, request
262
+ )
263
+ content = {"success": success, "message": message}
264
+ if success:
265
+ return ORJSONResponse(
266
+ content,
267
+ status_code=HTTPStatus.OK,
268
+ )
269
+ else:
270
+ return ORJSONResponse(
271
+ content,
272
+ status_code=HTTPStatus.BAD_REQUEST,
273
+ )
274
+
275
+
276
+ @app.post("/init_weights_update_group")
277
+ async def init_weights_update_group(
278
+ obj: InitWeightsUpdateGroupReqInput, request: Request
279
+ ):
280
+ """Initialize the parameter update group."""
281
+ success, message = await _global_state.tokenizer_manager.init_weights_update_group(
282
+ obj, request
283
+ )
284
+ content = {"success": success, "message": message}
285
+ if success:
286
+ return ORJSONResponse(content, status_code=200)
287
+ else:
288
+ return ORJSONResponse(content, status_code=HTTPStatus.BAD_REQUEST)
289
+
290
+
291
+ @app.post("/update_weights_from_distributed")
292
+ async def update_weights_from_distributed(
293
+ obj: UpdateWeightsFromDistributedReqInput, request: Request
294
+ ):
295
+ """Update model parameter from distributed online."""
296
+ success, message = (
297
+ await _global_state.tokenizer_manager.update_weights_from_distributed(
298
+ obj, request
299
+ )
300
+ )
301
+ content = {"success": success, "message": message}
302
+ if success:
303
+ return ORJSONResponse(content, status_code=200)
304
+ else:
305
+ return ORJSONResponse(content, status_code=HTTPStatus.BAD_REQUEST)
306
+
307
+
308
+ @app.api_route("/get_weights_by_name", methods=["GET", "POST"])
309
+ async def get_weights_by_name(obj: GetWeightsByNameReqInput, request: Request):
310
+ """Get model parameter by name."""
311
+ try:
312
+ ret = await _global_state.tokenizer_manager.get_weights_by_name(obj, request)
313
+ if ret is None:
314
+ return _create_error_response("Get parameter by name failed")
315
+ else:
316
+ return ORJSONResponse(ret, status_code=200)
317
+ except Exception as e:
318
+ return _create_error_response(e)
319
+
320
+
321
+ @app.api_route("/release_memory_occupation", methods=["GET", "POST"])
322
+ async def release_memory_occupation(
323
+ obj: ReleaseMemoryOccupationReqInput, request: Request
324
+ ):
325
+ """Release GPU occupation temporarily"""
326
+ try:
327
+ await _global_state.tokenizer_manager.release_memory_occupation(obj, request)
328
+ except Exception as e:
329
+ return _create_error_response(e)
330
+
331
+
332
+ @app.api_route("/resume_memory_occupation", methods=["GET", "POST"])
333
+ async def resume_memory_occupation(
334
+ obj: ResumeMemoryOccupationReqInput, request: Request
335
+ ):
336
+ """Resume GPU occupation"""
337
+ try:
338
+ await _global_state.tokenizer_manager.resume_memory_occupation(obj, request)
339
+ except Exception as e:
340
+ return _create_error_response(e)
341
+
342
+
343
+ @app.api_route("/open_session", methods=["GET", "POST"])
344
+ async def open_session(obj: OpenSessionReqInput, request: Request):
345
+ """Open a session, and return its unique session id."""
346
+ try:
347
+ session_id = await _global_state.tokenizer_manager.open_session(obj, request)
348
+ if session_id is None:
349
+ raise Exception(
350
+ "Failed to open the session. Check if a session with the same id is still open."
351
+ )
352
+ return session_id
353
+ except Exception as e:
354
+ return _create_error_response(e)
355
+
356
+
357
+ @app.api_route("/close_session", methods=["GET", "POST"])
358
+ async def close_session(obj: CloseSessionReqInput, request: Request):
359
+ """Close the session"""
360
+ try:
361
+ await _global_state.tokenizer_manager.close_session(obj, request)
362
+ return Response(status_code=200)
363
+ except Exception as e:
364
+ return _create_error_response(e)
365
+
366
+
367
+ @app.api_route("/configure_logging", methods=["GET", "POST"])
368
+ async def configure_logging(obj: ConfigureLoggingReq, request: Request):
369
+ """Close the session"""
370
+ _global_state.tokenizer_manager.configure_logging(obj)
371
+ return Response(status_code=200)
372
+
373
+
374
+ @app.post("/function_call")
375
+ async def function_call_request(obj: FunctionCallReqInput, request: Request):
376
+ """
377
+ A native API endpoint to parse function calls from a text.
378
+ """
379
+ # 1) Initialize the parser based on the request body
380
+ parser = FunctionCallParser(tools=obj.tools, tool_call_parser=obj.tool_call_parser)
381
+
382
+ # 2) Call the non-stream parsing method (non-stream)
383
+ normal_text, calls = parser.parse_non_stream(obj.text)
384
+
385
+ # 3) Organize the response content
386
+ response_data = {
387
+ "normal_text": normal_text,
388
+ "calls": [
389
+ call.model_dump() for call in calls
390
+ ], # Convert pydantic objects to dictionaries
391
+ }
392
+
393
+ return ORJSONResponse(content=response_data, status_code=200)
394
+
395
+
396
+ ##### OpenAI-compatible API endpoints #####
397
+
398
+
399
+ @app.post("/v1/completions")
400
+ async def openai_v1_completions(raw_request: Request):
401
+ return await v1_completions(_global_state.tokenizer_manager, raw_request)
402
+
403
+
404
+ @app.post("/v1/chat/completions")
405
+ async def openai_v1_chat_completions(raw_request: Request):
406
+ return await v1_chat_completions(_global_state.tokenizer_manager, raw_request)
407
+
408
+
409
+ @app.post("/v1/embeddings", response_class=ORJSONResponse)
410
+ async def openai_v1_embeddings(raw_request: Request):
411
+ response = await v1_embeddings(_global_state.tokenizer_manager, raw_request)
412
+ return response
413
+
414
+
415
+ @app.get("/v1/models", response_class=ORJSONResponse)
416
+ def available_models():
417
+ """Show available models."""
418
+ served_model_names = [_global_state.tokenizer_manager.served_model_name]
419
+ model_cards = []
420
+ for served_model_name in served_model_names:
421
+ model_cards.append(ModelCard(id=served_model_name, root=served_model_name))
422
+ return ModelList(data=model_cards)
423
+
424
+
425
+ @app.post("/v1/files")
426
+ async def openai_v1_files(file: UploadFile = File(...), purpose: str = Form("batch")):
427
+ return await v1_files_create(
428
+ file, purpose, _global_state.tokenizer_manager.server_args.file_storage_pth
429
+ )
430
+
431
+
432
+ @app.delete("/v1/files/{file_id}")
433
+ async def delete_file(file_id: str):
434
+ # https://platform.openai.com/docs/api-reference/files/delete
435
+ return await v1_delete_file(file_id)
436
+
437
+
438
+ @app.post("/v1/batches")
439
+ async def openai_v1_batches(raw_request: Request):
440
+ return await v1_batches(_global_state.tokenizer_manager, raw_request)
441
+
442
+
443
+ @app.post("/v1/batches/{batch_id}/cancel")
444
+ async def cancel_batches(batch_id: str):
445
+ # https://platform.openai.com/docs/api-reference/batch/cancel
446
+ return await v1_cancel_batch(_global_state.tokenizer_manager, batch_id)
447
+
448
+
449
+ @app.get("/v1/batches/{batch_id}")
450
+ async def retrieve_batch(batch_id: str):
451
+ return await v1_retrieve_batch(batch_id)
452
+
453
+
454
+ @app.get("/v1/files/{file_id}")
455
+ async def retrieve_file(file_id: str):
456
+ # https://platform.openai.com/docs/api-reference/files/retrieve
457
+ return await v1_retrieve_file(file_id)
458
+
459
+
460
+ @app.get("/v1/files/{file_id}/content")
461
+ async def retrieve_file_content(file_id: str):
462
+ # https://platform.openai.com/docs/api-reference/files/retrieve-contents
463
+ return await v1_retrieve_file_content(file_id)
464
+
465
+
466
+ def _create_error_response(e):
467
+ return ORJSONResponse(
468
+ {"error": {"message": str(e)}}, status_code=HTTPStatus.BAD_REQUEST
469
+ )
470
+
471
+
472
+ def launch_server(
473
+ server_args: ServerArgs,
474
+ pipe_finish_writer: Optional[multiprocessing.connection.Connection] = None,
475
+ ):
476
+ """
477
+ Launch SRT (SGLang Runtime) Server.
478
+
479
+ The SRT server consists of an HTTP server and an SRT engine.
480
+
481
+ - HTTP server: A FastAPI server that routes requests to the engine.
482
+ - The engine consists of three components:
483
+ 1. TokenizerManager: Tokenizes the requests and sends them to the scheduler.
484
+ 2. Scheduler (subprocess): Receives requests from the Tokenizer Manager, schedules batches, forwards them, and sends the output tokens to the Detokenizer Manager.
485
+ 3. DetokenizerManager (subprocess): Detokenizes the output tokens and sends the result back to the Tokenizer Manager.
486
+
487
+ Note:
488
+ 1. The HTTP server, Engine, and TokenizerManager both run in the main process.
489
+ 2. Inter-process communication is done through ICP (each process uses a different port) via the ZMQ library.
490
+ """
491
+ tokenizer_manager, scheduler_info = _launch_subprocesses(server_args=server_args)
492
+ set_global_state(
493
+ _GlobalState(
494
+ tokenizer_manager=tokenizer_manager,
495
+ scheduler_info=scheduler_info,
496
+ )
497
+ )
498
+
499
+ # Add api key authorization
500
+ if server_args.api_key:
501
+ add_api_key_middleware(app, server_args.api_key)
502
+
503
+ # Add prometheus middleware
504
+ if server_args.enable_metrics:
505
+ add_prometheus_middleware(app)
506
+ enable_func_timer()
507
+
508
+ # Send a warmup request
509
+ t = threading.Thread(
510
+ target=_wait_and_warmup,
511
+ args=(
512
+ server_args,
513
+ pipe_finish_writer,
514
+ _global_state.tokenizer_manager.image_token_id,
515
+ ),
516
+ )
517
+ t.start()
518
+
519
+ try:
520
+ # Update logging configs
521
+ set_uvicorn_logging_configs()
522
+
523
+ # Listen for HTTP requests
524
+ uvicorn.run(
525
+ app,
526
+ host=server_args.host,
527
+ port=server_args.port,
528
+ log_level=server_args.log_level_http or server_args.log_level,
529
+ timeout_keep_alive=5,
530
+ loop="uvloop",
531
+ )
532
+ finally:
533
+ t.join()
534
+
535
+
536
+ def _wait_and_warmup(server_args, pipe_finish_writer, image_token_text):
537
+ headers = {}
538
+ url = server_args.url()
539
+ if server_args.api_key:
540
+ headers["Authorization"] = f"Bearer {server_args.api_key}"
541
+
542
+ # Wait until the server is launched
543
+ success = False
544
+ for _ in range(120):
545
+ time.sleep(1)
546
+ try:
547
+ res = requests.get(url + "/get_model_info", timeout=5, headers=headers)
548
+ assert res.status_code == 200, f"{res=}, {res.text=}"
549
+ success = True
550
+ break
551
+ except (AssertionError, requests.exceptions.RequestException):
552
+ last_traceback = get_exception_traceback()
553
+ pass
554
+
555
+ if not success:
556
+ if pipe_finish_writer is not None:
557
+ pipe_finish_writer.send(last_traceback)
558
+ logger.error(f"Initialization failed. warmup error: {last_traceback}")
559
+ kill_process_tree(os.getpid())
560
+ return
561
+
562
+ model_info = res.json()
563
+
564
+ # Send a warmup request
565
+ request_name = "/generate" if model_info["is_generation"] else "/encode"
566
+ max_new_tokens = 8 if model_info["is_generation"] else 1
567
+ json_data = {
568
+ "sampling_params": {
569
+ "temperature": 0,
570
+ "max_new_tokens": max_new_tokens,
571
+ },
572
+ }
573
+ if server_args.skip_tokenizer_init:
574
+ json_data["input_ids"] = [10, 11, 12]
575
+ else:
576
+ json_data["text"] = "The capital city of France is"
577
+
578
+ try:
579
+ for _ in range(server_args.dp_size):
580
+ res = requests.post(
581
+ url + request_name,
582
+ json=json_data,
583
+ headers=headers,
584
+ timeout=600,
585
+ )
586
+ assert res.status_code == 200, f"{res}"
587
+ except Exception:
588
+ last_traceback = get_exception_traceback()
589
+ if pipe_finish_writer is not None:
590
+ pipe_finish_writer.send(last_traceback)
591
+ logger.error(f"Initialization failed. warmup error: {last_traceback}")
592
+ kill_process_tree(os.getpid())
593
+ return
594
+
595
+ # Debug print
596
+ # logger.info(f"{res.json()=}")
597
+
598
+ logger.info("The server is fired up and ready to roll!")
599
+ if pipe_finish_writer is not None:
600
+ pipe_finish_writer.send("ready")
601
+
602
+ if server_args.delete_ckpt_after_loading:
603
+ delete_directory(server_args.model_path)