vllm_mlx.server¶
Unified OpenAI-compatible API server for vllm-mlx.
View the complete module source at #L1-L6916.
API details¶
Each callable below includes its exact signature, type annotations, inputs, defaults, return contract, documented exceptions, implementation source, and parsed docstring sections when the source provides them.
vllm_mlx.server
¶
Unified OpenAI-compatible API server for vllm-mlx.
This module provides a FastAPI server that exposes an OpenAI-compatible API for LLM and MLLM (Multimodal Language Model) inference using MLX on Apple Silicon.
Supports two modes: - Simple mode (default): Maximum throughput for single-user scenarios - Batched mode: Continuous batching for multiple concurrent users
Features: - Text-only LLM inference (mlx-lm) - Multimodal MLLM inference with images and video (mlx-vlm) - OpenAI-compatible chat/completions API - Streaming responses - MCP (Model Context Protocol) tool integration - Tool calling (Qwen/Llama formats)
Usage
Simple mode (maximum throughput)¶
python -m vllm_mlx.server --model mlx-community/Llama-3.2-3B-Instruct-4bit
Batched mode (for multiple concurrent users)¶
python -m vllm_mlx.server --model mlx-community/Llama-3.2-3B-Instruct-4bit --continuous-batching
With MCP tools¶
python -m vllm_mlx.server --model mlx-community/Qwen3-4B-4bit --mcp-config mcp.json
The server provides
- POST /v1/completions - Text completions
- POST /v1/chat/completions - Chat completions (with multimodal support)
- GET /v1/models - List available models
- GET /health - Health check
- GET /v1/mcp/tools - List MCP tools
- GET /v1/mcp/servers - MCP server status
- POST /v1/mcp/execute - Execute MCP tool
vllm_mlx.server._default_chat_template_kwargs
module-attribute
¶
vllm_mlx.server._default_presence_penalty
module-attribute
¶
vllm_mlx.server._default_repetition_penalty
module-attribute
¶
vllm_mlx.server._max_audio_upload_bytes
module-attribute
¶
_max_audio_upload_bytes: int = DEFAULT_MAX_AUDIO_UPLOAD_BYTES
vllm_mlx.server._max_tts_input_chars
module-attribute
¶
_max_tts_input_chars: int = DEFAULT_MAX_TTS_INPUT_CHARS
vllm_mlx.server._default_thinking_token_budget
module-attribute
¶
vllm_mlx.server._residency_manager
module-attribute
¶
_residency_manager: ResidencyManager | None = None
vllm_mlx.server._embedding_model_locked
module-attribute
¶
vllm_mlx.server._responses_store
module-attribute
¶
vllm_mlx.server._TOOL_MARKUP_PATTERN
module-attribute
¶
vllm_mlx.server._STREAMING_TOOL_MARKERS
module-attribute
¶
_STREAMING_TOOL_MARKERS = ('<tool_call>', '<|tool_call>', '<function=', '[Calling tool:', '[TOOL_CALLS]', '<minimax:tool_call>', '<invoke name="', '<|channel|>commentary', '<|call|>')
vllm_mlx.server._STREAMING_BARE_BRACKET_MARKER
module-attribute
¶
vllm_mlx.server._STREAMING_BARE_BRACKET_PARTIAL
module-attribute
¶
vllm_mlx.server._STREAMING_TOOL_MARKUP_SCAN_CHARS
module-attribute
¶
vllm_mlx.server.app
module-attribute
¶
app = FastAPI(title='vllm-mlx API', description='OpenAI-compatible API for MLX LLM/MLLM inference on Apple Silicon', version='0.4.1', lifespan=lifespan)
vllm_mlx.server._rate_limiter
module-attribute
¶
_rate_limiter = RateLimiter(requests_per_minute=60, enabled=False)
vllm_mlx.server._HARMONY_ANALYSIS_BLOCK_RE
module-attribute
¶
_HARMONY_ANALYSIS_BLOCK_RE = re.compile('<\\|channel\\|>analysis[^<]*(?:<\\|constrain\\|>[^<]*)?<\\|message\\|>.*?(?=<\\|channel\\|>|<\\|end\\|>|\\Z)', re.DOTALL)
vllm_mlx.server._active_request_contexts
module-attribute
¶
_active_request_contexts: dict[int, RequestModelContext] = {}
vllm_mlx.server.PreparedChatInvocation
dataclass
¶
PreparedChatInvocation(messages: list[dict], chat_kwargs: dict[str, object], response_format: object | None, json_logits_processor: object | None, thinking_processor: object | None = None)
Fully prepared inputs for a single engine.chat/stream_chat call.
vllm_mlx.server.PreparedChatInvocation.chat_kwargs
instance-attribute
¶
vllm_mlx.server.PreparedChatInvocation.response_format
instance-attribute
¶
vllm_mlx.server.PreparedChatInvocation.json_logits_processor
instance-attribute
¶
vllm_mlx.server.PreparedChatInvocation.thinking_processor
class-attribute
instance-attribute
¶
vllm_mlx.server._ThinkingAwareLogitsProcessor
¶
Wrap a JSONSchemaLogitsProcessor so JSON constraining only activates
after the model emits </think>, letting it reason freely first.
Without this wrapper enable_thinking is forced to False when
constrained decoding is active, which degrades output for thinking models
(Qwen 3.5/3.6, DeepSeek-R1, etc.) — the model produces degenerated
whitespace/brace loops instead of valid JSON because it was trained to
think before answering.
Source code in vllm_mlx/server.py
vllm_mlx.server._ThinkingAwareLogitsProcessor._in_thinking
instance-attribute
¶
vllm_mlx.server._ThinkingAwareLogitsProcessor._waiting_for_json
instance-attribute
¶
vllm_mlx.server._ThinkingAwareLogitsProcessor._base_prompt_len
instance-attribute
¶
vllm_mlx.server._ThinkingAwareLogitsProcessor._json_scan_offset
instance-attribute
¶
vllm_mlx.server._ThinkingAwareLogitsProcessor._tokenizer
instance-attribute
¶
vllm_mlx.server._ThinkingAwareLogitsProcessor._scan_for_json_start
¶
Scan generated tokens for the first { or [.
Scans from _json_scan_offset (set when entering the waiting
phase) so that thinking-span tokens are never considered. After
50 tokens past the scan offset without a JSON start character the
enforcer is force-activated as a safety net.
Source code in vllm_mlx/server.py
vllm_mlx.server._ThinkingAwareLogitsProcessor.__call__
¶
Source code in vllm_mlx/server.py
vllm_mlx.server.RequestModelContext
dataclass
¶
RequestModelContext(model_name: str, engine: BaseEngine, lease: ModelLease | None = None)
Request-scoped engine/lease context.
vllm_mlx.server.RequestModelContext.lease
class-attribute
instance-attribute
¶
lease: ModelLease | None = None
vllm_mlx.server.RequestModelContext.release
async
¶
Release the registry lease once, if this context owns one.
vllm_mlx.server.RateLimiter
¶
Simple in-memory rate limiter using sliding window.
Source code in vllm_mlx/server.py
vllm_mlx.server.RateLimiter.requests_per_minute
instance-attribute
¶
vllm_mlx.server.RateLimiter._requests
instance-attribute
¶
vllm_mlx.server.RateLimiter.is_allowed
¶
Check if request is allowed for client.
Returns:
-
tuple[bool, int]–(is_allowed, retry_after_seconds)
Source code in vllm_mlx/server.py
vllm_mlx.server._resolve_temperature
¶
Resolve temperature: request > CLI default > fallback.
Source code in vllm_mlx/server.py
vllm_mlx.server._resolve_top_p
¶
Resolve top_p: request > CLI default > fallback.
Source code in vllm_mlx/server.py
vllm_mlx.server._resolve_top_k
¶
Resolve top_k: request > CLI default > fallback.
vllm_mlx.server._resolve_min_p
¶
Resolve min_p: request > CLI default > fallback.
Source code in vllm_mlx/server.py
vllm_mlx.server._resolve_presence_penalty
¶
Resolve presence_penalty: request > CLI default > fallback.
Source code in vllm_mlx/server.py
vllm_mlx.server._resolve_repetition_penalty
¶
Resolve repetition_penalty: request > CLI default > fallback.
Source code in vllm_mlx/server.py
vllm_mlx.server._resolve_request_max_tokens
¶
Resolve and validate a request's max_tokens budget.
Source code in vllm_mlx/server.py
vllm_mlx.server._resolve_chat_template_kwargs
¶
Resolve chat template kwargs: request > server default > empty dict.
Source code in vllm_mlx/server.py
vllm_mlx.server._prepare_chat_messages
¶
_prepare_chat_messages(engine: BaseEngine, request_messages: list[Message | dict]) -> tuple[list[dict], list, list, list, bool]
Normalize messages and collect media once for both stream/non-stream paths.
Source code in vllm_mlx/server.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | |
vllm_mlx.server._iter_remote_media_urls
¶
_iter_remote_media_urls(messages: list[Message | dict])
Yield remote media URLs from OpenAI-style multimodal message content.
Source code in vllm_mlx/server.py
vllm_mlx.server._validate_remote_media_urls
¶
_validate_remote_media_urls(messages: list[Message | dict]) -> None
Validate remote media URLs during request preparation.
vllm_mlx.server._raise_remote_media_http_error
¶
_raise_remote_media_http_error(exc: UnsafeRemoteURLError) -> None
Log internal URL-safety detail while returning a generic client error.
Source code in vllm_mlx/server.py
vllm_mlx.server._prepare_json_logits_processor
¶
_prepare_json_logits_processor(engine: BaseEngine, messages: list[dict], response_format: object | None, *, tools: list | None, tool_choice: object | None, log_context: str | None = None, thinking_model: bool = False) -> tuple[list[dict], object | None]
Inject response_format instruction and build constrained decoding processor.
Source code in vllm_mlx/server.py
vllm_mlx.server._build_thinking_processor
¶
_build_thinking_processor(engine: BaseEngine, thinking_token_budget: int, *, inner: object | None = None, prompt_has_think_tag: bool = True) -> object | None
Build a ThinkingAwareLogitsProcessor if the tokenizer has think tokens.
Source code in vllm_mlx/server.py
vllm_mlx.server._resolve_no_final_content_token_limit
¶
Source code in vllm_mlx/server.py
vllm_mlx.server._generation_metadata
¶
_generation_metadata(thinking_processor: object | None) -> GenerationMetadata | None
Source code in vllm_mlx/server.py
vllm_mlx.server._attach_response_format_logits_processor
¶
_attach_response_format_logits_processor(chat_kwargs: dict, json_logits_processor: object) -> object
Attach response_format constraints and keep thinking disabled.
response_format content must be constrained from the first generated token. If the processor is hidden behind thinking-state handling, direct JSON emissions can bypass the constraint and run until max_tokens.
Source code in vllm_mlx/server.py
vllm_mlx.server._coerce_logit_bias
¶
Source code in vllm_mlx/server.py
vllm_mlx.server._attach_logit_bias_processor
¶
Source code in vllm_mlx/server.py
vllm_mlx.server._prepare_chat_completion_invocation
¶
_prepare_chat_completion_invocation(engine: BaseEngine, request: ChatCompletionRequest, effective_max_tokens: int) -> PreparedChatInvocation
Precompute messages, kwargs, and decoding constraints for chat completions.
Source code in vllm_mlx/server.py
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 | |
vllm_mlx.server._prepare_anthropic_invocation
¶
_prepare_anthropic_invocation(engine: BaseEngine, openai_request: ChatCompletionRequest, effective_max_tokens: int) -> PreparedChatInvocation
Precompute messages, kwargs, and decoding constraints for Anthropic API.
Source code in vllm_mlx/server.py
vllm_mlx.server._thinking_disabled
¶
Return True iff thinking is explicitly disabled for this request.
Checks both the request-level enable_thinking field and the resolved
chat_template_kwargs (which may carry the server-wide default set via
--default-chat-template-kwargs). When thinking is disabled the prompt
contains no injected <think> block, so the streaming reasoning parser
must not default to implicit-thinking mode and swallow plain content into
a thinking block.
Source code in vllm_mlx/server.py
vllm_mlx.server._strip_backslash_before_unicode
¶
Remove spurious backslashes before non-ASCII chars in JSON string values.
lm-format-enforcer's grammar allows \ (valid JSON escape) followed by
non-ASCII characters such as Korean syllables. The model therefore generates
\빠\르\게 — valid JSON whose decoded value contains literal backslashes.
This helper strips those spurious backslashes so clients receive clean text.
Source code in vllm_mlx/server.py
vllm_mlx.server._sanitize_log_text
¶
Escape control characters before logging untrusted text.
Source code in vllm_mlx/server.py
vllm_mlx.server._log_and_raise_internal_error
¶
Log a sanitized exception string and raise a generic 500 response.
Source code in vllm_mlx/server.py
vllm_mlx.server._raise_engine_busy
¶
_raise_engine_busy(exc: EngineBusy) -> None
Translate serialized-engine admission failures into retryable HTTP 503.
Source code in vllm_mlx/server.py
vllm_mlx.server._list_available_model_names
¶
vllm_mlx.server._response_model_name
¶
vllm_mlx.server._acquire_request_model
async
¶
_acquire_request_model(request_model: str) -> RequestModelContext
Acquire the model/engine that should serve this request.
Source code in vllm_mlx/server.py
vllm_mlx.server._stream_with_model_context
async
¶
_stream_with_model_context(context: RequestModelContext, stream: AsyncIterator[str]) -> AsyncIterator[str]
Ensure model leases survive for the full streaming response.
Source code in vllm_mlx/server.py
vllm_mlx.server._build_tool_parser
¶
_build_tool_parser(engine: BaseEngine | None)
Create a fresh tool parser instance for a single request/stream.
Source code in vllm_mlx/server.py
vllm_mlx.server._build_reasoning_parser
¶
_build_reasoning_parser(engine: BaseEngine | None = None)
Create a fresh reasoning parser instance for a single request/stream.
Source code in vllm_mlx/server.py
vllm_mlx.server._prepare_streaming_reasoning_parser
¶
_prepare_streaming_reasoning_parser(engine: BaseEngine, request: ChatCompletionRequest | ResponsesRequest | None, chat_kwargs: dict[str, object], *, allowed: bool = True)
Build and reset request-local reasoning state when thinking is enabled.
Source code in vllm_mlx/server.py
vllm_mlx.server._prepare_openai_stream_reasoning_state
¶
_prepare_openai_stream_reasoning_state(engine: BaseEngine, request: ChatCompletionRequest, chat_kwargs: dict[str, object]) -> tuple[object | None, bool]
Return request-local reasoning state and the legacy Nemotron marker state.
Source code in vllm_mlx/server.py
vllm_mlx.server._request_tool_definitions
¶
_request_tool_definitions(request: ChatCompletionRequest) -> list | None
Return the request tool schema once for streaming argument coercion.
Source code in vllm_mlx/server.py
vllm_mlx.server._streaming_json_fence_stripper
¶
_streaming_json_fence_stripper(request: ChatCompletionRequest) -> StreamingJsonFenceStripper | None
Create a fence stripper only for JSON-constrained streaming responses.
Source code in vllm_mlx/server.py
vllm_mlx.server._get_idle_unload_event
¶
Return the idle-unload gate event, creating it on first use.
The returned Event is bound to the running loop at creation time.
Reset _idle_unload_enabled to None when tearing down the
server or switching event loops (e.g. in test fixtures).
Source code in vllm_mlx/server.py
vllm_mlx.server._invalidate_tool_parser_cache
¶
Drop cached parser state when the serving tokenizer changes.
Source code in vllm_mlx/server.py
vllm_mlx.server._load_prefix_cache_from_disk
¶
_load_prefix_cache_from_disk(engine: BaseEngine | None = None) -> None
Load prefix cache from disk during startup.
Source code in vllm_mlx/server.py
vllm_mlx.server._save_prefix_cache_to_disk
¶
_save_prefix_cache_to_disk(engine: BaseEngine | None = None) -> None
Save prefix cache to disk during shutdown.
Source code in vllm_mlx/server.py
vllm_mlx.server._get_cache_dir
¶
Get cache persistence directory based on actual model path.
Source code in vllm_mlx/server.py
vllm_mlx.server._build_engine
¶
_build_engine(spec: ModelSpec) -> BaseEngine
Construct an engine instance from a model spec without starting it.
Source code in vllm_mlx/server.py
vllm_mlx.server._engine_factory
async
¶
_engine_factory(spec: ModelSpec) -> BaseEngine
vllm_mlx.server._run_blocking_engine_cache_io
async
¶
_run_blocking_engine_cache_io(io_fn, engine: BaseEngine) -> None
Run blocking cache persistence off the event loop.
If the caller is canceled while waiting, finish the in-flight thread before propagating cancellation so engine state cannot keep mutating in the background after lifecycle cleanup has started.
Source code in vllm_mlx/server.py
vllm_mlx.server._restore_engine_state
async
¶
_restore_engine_state(spec: ModelSpec, engine: BaseEngine) -> None
Restore engine-local state, such as prefix cache, after a cold load.
Source code in vllm_mlx/server.py
vllm_mlx.server._persist_engine_state
async
¶
_persist_engine_state(spec: ModelSpec, engine: BaseEngine) -> None
Persist engine-local state before an idle unload or shutdown unload.
Source code in vllm_mlx/server.py
vllm_mlx.server._activate_engine
¶
_activate_engine(engine: BaseEngine | None) -> BaseEngine | None
Set the global engine pointer and refresh parser-sensitive state.
Source code in vllm_mlx/server.py
vllm_mlx.server._sync_engine_from_residency
¶
_sync_engine_from_residency() -> BaseEngine | None
Sync the global engine pointer from the residency manager state.
Safety: all callers run on the single-threaded asyncio event loop and do not
yield between reading the residency state and writing _engine, so no
additional locking is required.
Source code in vllm_mlx/server.py
vllm_mlx.server._get_lifecycle_status
¶
Get lifecycle status for the default resident if lifecycle is enabled.
Source code in vllm_mlx/server.py
vllm_mlx.server._public_lifecycle_status
¶
Return residency status safe for unauthenticated public endpoints.
Source code in vllm_mlx/server.py
vllm_mlx.server._lifecycle_loop
async
¶
Background idle-unload loop for the default resident.
Source code in vllm_mlx/server.py
vllm_mlx.server._acquire_default_engine
async
¶
_acquire_default_engine(*, count_activity: bool = True) -> BaseEngine
Acquire the default engine, auto-loading via the residency manager if needed.
Source code in vllm_mlx/server.py
vllm_mlx.server._release_default_engine
async
¶
Release the default engine after request processing.
Source code in vllm_mlx/server.py
vllm_mlx.server.lifespan
async
¶
FastAPI lifespan for startup/shutdown events.
Source code in vllm_mlx/server.py
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 | |
vllm_mlx.server._metrics_result_from_status
¶
Map HTTP-ish status codes to low-cardinality inference results.
Source code in vllm_mlx/server.py
vllm_mlx.server._metrics_path_for_request
¶
Prefer route templates over raw URLs to keep metrics cardinality bounded.
Source code in vllm_mlx/server.py
vllm_mlx.server._metrics_middleware
async
¶
Capture generic HTTP request metrics when enabled.
Source code in vllm_mlx/server.py
vllm_mlx.server.check_rate_limit
async
¶
Rate limiting dependency.
Source code in vllm_mlx/server.py
vllm_mlx.server.verify_api_key
async
¶
verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security))
Verify API key if authentication is enabled.
Source code in vllm_mlx/server.py
vllm_mlx.server.get_engine
¶
get_engine() -> BaseEngine
vllm_mlx.server._coerce_tool_arguments
¶
Coerce tool call arguments to match the tool schema.
If a schema field expects "string" but the model produced an object/array, JSON-stringify the value. This fixes a common LLM failure mode where models output raw JSON objects instead of JSON strings for file content, etc.
Source code in vllm_mlx/server.py
vllm_mlx.server._validate_model_name
¶
Validate that the request model name matches the served model.
Source code in vllm_mlx/server.py
vllm_mlx.server._get_engine_tokenizer
¶
Return the tokenizer backing engine, if exposed.
Different engine classes store the tokenizer under different attributes.
We try the common ones and return None if nothing matches, so that
optional features like constrained decoding can degrade gracefully.
Source code in vllm_mlx/server.py
vllm_mlx.server._get_or_init_tool_parser
¶
_get_or_init_tool_parser(engine: BaseEngine | None = None)
Return the cached tool parser, initializing it from the given engine.
Source code in vllm_mlx/server.py
vllm_mlx.server._parse_tool_calls_with_parser
¶
_parse_tool_calls_with_parser(output_text: str, request: ChatCompletionRequest | None = None, engine: BaseEngine | None = None) -> tuple[str, list | None]
Parse tool calls from model output using the configured parser.
If --enable-auto-tool-choice is set with --tool-call-parser, uses the selected parser. Otherwise falls back to the generic parse_tool_calls.
Parameters:
-
output_text(str) –The model output text
-
request(ChatCompletionRequest | None, default:None) –The original request (for context)
-
engine(BaseEngine | None, default:None) –The request-local engine to use for parser initialization
Returns:
-
tuple[str, list | None]–Tuple of (cleaned_text, tool_calls)
Source code in vllm_mlx/server.py
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 | |
vllm_mlx.server._apply_response_format_or_raise
¶
_apply_response_format_or_raise(text: str, response_format: object, *, ensure_ascii: bool = False) -> str
Return validated JSON content or fail before returning a success response.
Source code in vllm_mlx/server.py
vllm_mlx.server._response_format_type
¶
vllm_mlx.server._promote_streaming_response_format_delta
¶
_promote_streaming_response_format_delta(content: str | None, reasoning: str | None, request: ChatCompletionRequest) -> tuple[str | None, str | None]
Keep response_format JSON on the streaming content channel.
Some thinking parsers classify direct JSON output as reasoning when the model emits JSON without an explicit reasoning end marker. For response_format requests, that JSON is the final assistant content.
Source code in vllm_mlx/server.py
vllm_mlx.server._new_response_item_id
¶
vllm_mlx.server._response_content_to_text
¶
Normalize Responses API content items into plain text.
Source code in vllm_mlx/server.py
vllm_mlx.server._responses_tools_to_chat_tools
¶
_responses_tools_to_chat_tools(tools: list[ResponseFunctionTool | dict]) -> tuple[list[dict] | None, list[str]]
Convert supported Responses tools and report unsupported tool types.
Source code in vllm_mlx/server.py
vllm_mlx.server._responses_input_to_chat_messages
¶
_responses_input_to_chat_messages(request: ResponsesRequest) -> list[dict]
Convert Responses API input items into chat-completions-style messages.
Source code in vllm_mlx/server.py
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 | |
vllm_mlx.server._responses_request_to_new_persisted_messages
¶
_responses_request_to_new_persisted_messages(request: ResponsesRequest) -> list[dict]
Persist only the current request's replayable input items.
Source code in vllm_mlx/server.py
vllm_mlx.server._responses_request_to_persisted_messages
¶
_responses_request_to_persisted_messages(request: ResponsesRequest) -> list[dict]
Persist replayable history for chained previous_response_id requests.
Responses instructions are intentionally not replayed across
previous_response_id, but replayable message items are.
Source code in vllm_mlx/server.py
vllm_mlx.server._responses_request_to_chat_request
¶
_responses_request_to_chat_request(request: ResponsesRequest) -> ChatCompletionRequest
Build a ChatCompletionRequest from a ResponsesRequest.
Source code in vllm_mlx/server.py
vllm_mlx.server._build_responses_output_items
¶
_build_responses_output_items(text: str | None, reasoning: str | None, tool_calls: list[ToolCall] | None) -> list[ResponseMessageItem | ResponseReasoningItem | ResponseFunctionCallItem]
Convert parsed assistant output into Responses API output items.
Source code in vllm_mlx/server.py
vllm_mlx.server._response_output_items_to_chat_messages
¶
Persist assistant output in chat-completions form for previous_response_id.
Source code in vllm_mlx/server.py
vllm_mlx.server._build_response_object
¶
_build_response_object(request: ResponsesRequest, output_items: list[ResponseMessageItem | ResponseReasoningItem | ResponseFunctionCallItem], prompt_tokens: int, completion_tokens: int, finish_reason: str | None, response_id: str | None = None) -> ResponseObject
Build a full Responses API object.
Source code in vllm_mlx/server.py
vllm_mlx.server._prepare_responses_request
¶
_prepare_responses_request(request: ResponsesRequest, *, validate_remote_media: bool = True) -> tuple[BaseEngine, ChatCompletionRequest, list[dict], dict]
Prepare a Responses request for execution on the chat engine.
Source code in vllm_mlx/server.py
vllm_mlx.server._prepare_streaming_responses_request
¶
_prepare_streaming_responses_request(request: ResponsesRequest) -> tuple[BaseEngine, ChatCompletionRequest, list[dict], dict]
Prepare a streaming Responses request after eager URL validation.
Source code in vllm_mlx/server.py
vllm_mlx.server._run_responses_request
async
¶
_run_responses_request(request: ResponsesRequest, raw_request: Request) -> tuple[ResponseObject | None, list[dict]]
Execute a Responses API request against the backend chat engine.
Source code in vllm_mlx/server.py
vllm_mlx.server._stream_responses_request
async
¶
_stream_responses_request(request: ResponsesRequest) -> AsyncIterator[str]
Execute a Responses API request and stream SSE events incrementally.
Source code in vllm_mlx/server.py
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 | |
vllm_mlx.server._responses_sse_event
¶
Encode a Responses API SSE event.
Source code in vllm_mlx/server.py
vllm_mlx.server._strip_harmony_analysis_blocks
¶
Remove harmony analysis-channel blocks (and their content) so reasoning text is never handed to the tool parser, while commentary/final text is preserved.
Source code in vllm_mlx/server.py
vllm_mlx.server._extract_reasoning_and_tool_calls
¶
_extract_reasoning_and_tool_calls(output_text: str, request: ChatCompletionRequest | None = None, *, allow_reasoning: bool = True, engine: BaseEngine | None = None) -> tuple[str | None, str | None, list[ToolCall] | None]
Extract reasoning first, then parse tool calls from the cleaned content.
Non-streaming responses can contain both a reasoning block and structured tool calls in the same final output. If tool parsing runs first and the response contains tools, the caller can no longer reliably recover the reasoning segment because the usual response path skips reasoning parsing once tool_calls is truthy.
Source code in vllm_mlx/server.py
vllm_mlx.server._detect_native_tool_support
¶
Detect if the active tool parser supports native tool format.
Native format means role="tool" messages and tool_calls fields are preserved instead of being converted to text.
Returns:
-
bool–True if native format should be preserved
Source code in vllm_mlx/server.py
vllm_mlx.server._detect_harmony_rendering
¶
Detect whether the harmony rendering path should handle prompt building.
Returns True when ALL of:
- --tool-call-parser is set to harmony or gpt-oss
- --enable-auto-tool-choice is on
- the optional openai-harmony Python package is importable
The third condition keeps non-gpt-oss deployments free of an extra
runtime dependency: if the package isn't installed, the engine falls
back to the standard tokenizer.apply_chat_template path. The
HarmonyToolParser's existing text-flatten behavior also stays in force
in that fallback so the response side is unchanged.
Source code in vllm_mlx/server.py
vllm_mlx.server._tool_choice_disabled
¶
_tool_choice_disabled(request: ChatCompletionRequest | None) -> bool
Return True when tool_choice explicitly disables tool calling.
Source code in vllm_mlx/server.py
vllm_mlx.server._get_streaming_tool_parser
¶
_get_streaming_tool_parser(request: ChatCompletionRequest | None, engine: BaseEngine | None = None)
Get a streaming-capable tool parser for this request.
Uses the configured parser when auto tool choice is enabled, otherwise falls back to the generic auto parser so streaming still matches the generic non-streaming tool parsing behavior.
Source code in vllm_mlx/server.py
vllm_mlx.server._extract_streaming_tool_delta
¶
_extract_streaming_tool_delta(parser, previous_text: str, delta_text: str, request_context: dict) -> tuple[str, dict | None]
Parse one request-local streaming delta and return new accumulated text.
Source code in vllm_mlx/server.py
vllm_mlx.server._stream_request_metadata
¶
_stream_request_metadata(request: ChatCompletionRequest) -> tuple[dict, list | None, bool]
Source code in vllm_mlx/server.py
vllm_mlx.server._parse_streaming_tool_content
¶
_parse_streaming_tool_content(parser, accumulated_text: str, delta_text: str, request_context: dict) -> tuple[str, dict | None, bool]
Source code in vllm_mlx/server.py
vllm_mlx.server._streaming_tool_markup_possible
¶
Heuristic marker check to avoid parser work on ordinary text chunks.
Source code in vllm_mlx/server.py
vllm_mlx.server._streaming_tool_markup_possible_after_delta
¶
Check only the boundary window needed to detect newly appearing tool markup.
Streaming paths call this before any marker has been seen. Scanning the full accumulated text on every ordinary chunk is quadratic for long responses, so keep enough trailing context to catch markers split across chunk boundaries. Once markup is possible, callers switch to the parser path with the full accumulated text.
Source code in vllm_mlx/server.py
vllm_mlx.server.load_embedding_model
¶
load_embedding_model(model_name: str | None, *, lock: bool = False, reuse_existing: bool = True) -> None
Load or reuse the embedding model engine when configured.
Source code in vllm_mlx/server.py
vllm_mlx.server.load_reranker_model
¶
load_reranker_model(model_name: str | None, *, lock: bool = False, reuse_existing: bool = True) -> None
Load or reuse the reranker model engine when configured.
Source code in vllm_mlx/server.py
vllm_mlx.server.load_model
¶
load_model(model_name: str, use_batching: bool = False, scheduler_config=None, stream_interval: int = 1, max_tokens: int = 32768, max_request_tokens: int = 32768, force_mllm: bool = False, gpu_memory_utilization: float = 0.9, served_model_name: str | None = None, trust_remote_code: bool = False, mtp: bool = False, prefill_step_size: int = 2048, specprefill_enabled: bool = False, specprefill_threshold: int = 8192, specprefill_keep_pct: float = 0.3, specprefill_backbone_pct: float = 0.0, specprefill_draft_model: str = None, mllm_draft_model: str | None = None, mllm_draft_kind: str | None = None, mllm_draft_block_size: int | None = None, warm_prompts_path: str | None = None, auto_unload_idle_seconds: float = 0.0, lazy_load_model: bool = False)
Load a model (auto-detects MLLM vs LLM).
Parameters:
-
model_name(str) –HuggingFace model name or local path
-
use_batching(bool, default:False) –Use continuous batching (BatchedEngine) vs simple mode (SimpleEngine)
-
scheduler_config–Scheduler config for batched mode
-
stream_interval(int, default:1) –Tokens to batch before streaming (batched mode only)
-
max_tokens(int, default:32768) –Default max tokens for generation
-
max_request_tokens(int, default:32768) –Maximum max_tokens accepted from API clients
-
force_mllm(bool, default:False) –Force loading as MLLM even if not auto-detected
-
trust_remote_code(bool, default:False) –Allow HuggingFace remote code execution during model/tokenizer loading
-
mtp(bool, default:False) –Enable native MTP speculative decoding (SimpleEngine only)
-
prefill_step_size(int, default:2048) –Chunk size for prompt prefill processing (default: 2048)
-
specprefill_enabled(bool, default:False) –Enable SpecPrefill (SimpleEngine only)
-
specprefill_threshold(int, default:8192) –Minimum suffix tokens to trigger SpecPrefill (default: 8192)
-
specprefill_keep_pct(float, default:0.3) –Fraction of tokens to keep (default: 0.3)
-
specprefill_backbone_pct(float, default:0.0) –Fraction of chunks reserved for evenly spaced coverage
-
specprefill_draft_model(str, default:None) –Path to small draft model for SpecPrefill scoring
-
mllm_draft_model(str | None, default:None) –Optional MLLM speculative draft/assistant model path.
-
mllm_draft_kind(str | None, default:None) –Optional mlx-vlm draft kind, for example "mtp".
-
mllm_draft_block_size(int | None, default:None) –Optional speculative block size passed to mlx-vlm.
-
auto_unload_idle_seconds(float, default:0.0) –Idle time before auto-unloading the main model. When non-zero, the main model is managed through lifecycle residency instead of being loaded immediately in this function.
-
lazy_load_model(bool, default:False) –When lifecycle residency is enabled, defer the first resident load until the first request instead of FastAPI lifespan startup.
Source code in vllm_mlx/server.py
3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 | |
vllm_mlx.server.load_model_registry
¶
load_model_registry(config_path: str, *, defaults: RegistryServeDefaults) -> None
Load a registry-backed model manager from YAML configuration.
Source code in vllm_mlx/server.py
vllm_mlx.server.get_usage
¶
get_usage(output: GenerationOutput) -> Usage
Extract usage metrics from GenerationOutput.
Source code in vllm_mlx/server.py
vllm_mlx.server.metrics
async
¶
Prometheus scrape endpoint (disabled by default).
Source code in vllm_mlx/server.py
vllm_mlx.server.health
async
¶
Health check endpoint.
Source code in vllm_mlx/server.py
vllm_mlx.server.status
async
¶
Real-time status with per-request details for debugging and monitoring.
Source code in vllm_mlx/server.py
vllm_mlx.server.cache_stats
async
¶
Get cache statistics for debugging and monitoring.
Source code in vllm_mlx/server.py
vllm_mlx.server.clear_cache
async
¶
Clear all caches.
Source code in vllm_mlx/server.py
vllm_mlx.server.clear_prefix_cache
async
¶
Clear the text prefix cache used for KV reuse in continuous batching.
If the server was started with --warm-prompts, the warm-up is
re-run in the background after clear so the next real request still
hits the cache. Response returns immediately without waiting for
the re-warm to finish.
Source code in vllm_mlx/server.py
vllm_mlx.server.cancel_request
async
¶
Cancel an active or queued request.
The request_id is the chatcmpl-xxx ID from the first SSE streaming chunk.
Source code in vllm_mlx/server.py
vllm_mlx.server.delete_request
async
¶
OpenAI-style alias for cancelling an active or queued request.
Source code in vllm_mlx/server.py
vllm_mlx.server.list_models
async
¶
list_models() -> ModelsResponse
List available models.
Source code in vllm_mlx/server.py
vllm_mlx.server.create_embeddings
async
¶
create_embeddings(request: EmbeddingRequest) -> EmbeddingResponse
Create embeddings for the given input text(s).
OpenAI-compatible embeddings API supporting single or batch inputs.
Single text:
{
"model": "mlx-community/all-MiniLM-L6-v2-4bit",
"input": "The quick brown fox jumps over the lazy dog"
}
Batch of texts:
{
"model": "mlx-community/embeddinggemma-300m-6bit",
"input": [
"I love machine learning",
"Deep learning is fascinating",
"Neural networks are powerful"
]
}
Response:
{
"object": "list",
"data": [
{"object": "embedding", "index": 0, "embedding": [0.023, -0.982, ...]},
{"object": "embedding", "index": 1, "embedding": [0.112, -0.543, ...]},
{"object": "embedding", "index": 2, "embedding": [0.876, 0.221, ...]}
],
"model": "mlx-community/embeddinggemma-300m-6bit",
"usage": {"prompt_tokens": 24, "total_tokens": 24}
}
Supported request-time models: - mlx-community/all-MiniLM-L6-v2-4bit (fast, compact) - mlx-community/embeddinggemma-300m-6bit (high quality) - mlx-community/bge-large-en-v1.5-4bit (best for English) - mlx-community/multilingual-e5-small-mlx - mlx-community/multilingual-e5-large-mlx - mlx-community/bert-base-uncased-mlx - mlx-community/ModernBERT-base-mlx
Other embedding models must be pinned explicitly with --embedding-model at server startup.
Source code in vllm_mlx/server.py
3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 | |
vllm_mlx.server.rerank_documents
async
¶
rerank_documents(request: RerankRequest) -> RerankResponse
Rerank documents against a query using a cross-encoder model.
Jina/Cohere-compatible reranking API. Accepts a query and a list of documents (strings or {text: ...} objects), returns results sorted by relevance score descending.
Source code in vllm_mlx/server.py
3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 | |
vllm_mlx.server.list_mcp_tools
async
¶
list_mcp_tools() -> MCPToolsResponse
List all available MCP tools.
Source code in vllm_mlx/server.py
vllm_mlx.server.list_mcp_servers
async
¶
list_mcp_servers() -> MCPServersResponse
Get status of all MCP servers.
Source code in vllm_mlx/server.py
vllm_mlx.server.execute_mcp_tool
async
¶
execute_mcp_tool(request: MCPExecuteRequest) -> MCPExecuteResponse
Execute an MCP tool.
Source code in vllm_mlx/server.py
vllm_mlx.server.create_transcription
async
¶
create_transcription(file: UploadFile, model: str = 'whisper-large-v3', language: str | None = None, response_format: str = 'json')
Transcribe audio to text (OpenAI Whisper API compatible).
Supported models: - whisper-large-v3 (multilingual, best quality) - whisper-large-v3-turbo (faster) - whisper-medium, whisper-small (lighter) - parakeet-tdt-0.6b-v2 (English, fastest)
Source code in vllm_mlx/server.py
4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 | |
vllm_mlx.server.create_speech
async
¶
create_speech(model: str = 'kokoro', input: str = '', voice: str = 'af_heart', speed: float = 1.0, response_format: str = 'wav')
Generate speech from text (OpenAI TTS API compatible).
Supported models: - kokoro (fast, lightweight) - chatterbox (multilingual, expressive) - vibevoice (realtime) - voxcpm (Chinese/English)
Source code in vllm_mlx/server.py
vllm_mlx.server.list_voices
async
¶
List available voices for a TTS model.
Source code in vllm_mlx/server.py
vllm_mlx.server._ensure_sse_terminal
async
¶
Guarantee that terminal_frame is emitted exactly once at the end of generator, even if the generator raises mid-stream.
If the inner generator already yields the terminal frame on its happy path,
the wrapper detects it and avoids double-emission. If the generator raises
before reaching the terminal, the wrapper emits it in the finally block.
Source code in vllm_mlx/server.py
vllm_mlx.server._find_uvicorn_cycle
¶
Walk through middleware wrappers to find uvicorn's RequestResponseCycle.
This relies on uvicorn's internal RequestResponseCycle.disconnected
attribute and Starlette's middleware closure layout. Tested against
uvicorn 0.34-0.40 and starlette 0.44-0.46. If either changes the
internal layout, this function returns None and disconnect detection
silently falls back to timeout-only behaviour.
Source code in vllm_mlx/server.py
vllm_mlx.server._is_client_disconnected
¶
Reliable client disconnect check.
Starlette's is_disconnected() uses an immediately-cancelled
anyio.CancelScope which prevents the ASGI receive() from
executing — so it always returns False for non-streaming requests.
This function bypasses Starlette and reads uvicorn's internal
disconnected flag directly from the RequestResponseCycle,
walking through any middleware wrappers via closures.
Source code in vllm_mlx/server.py
vllm_mlx.server._disconnect_guard
async
¶
_disconnect_guard(generator: AsyncIterator[str], raw_request: Request, poll_interval: float = 0.5, heartbeat_interval: float = 5.0, cleanup=None, timeout: float | None = None) -> AsyncIterator[str]
Wrap streaming generator to abort on client disconnect.
Uses asyncio racing: each anext() on the inner generator is
raced against a disconnect poller. When neither completes within
heartbeat_interval seconds, an SSE comment is yielded as a
heartbeat. This forces an ASGI write which triggers broken-pipe
detection — without heartbeats, is_disconnected() stays False
during long prefill because no data is written to the socket.
If timeout is set, it bounds inactivity from the inner generator, not the total stream lifetime. A stream that continues to produce chunks must be allowed to complete even when generation takes longer than the configured interval. Heartbeats force ASGI writes to detect a disconnected client, but do not count as generator progress.
On disconnect, the cancellation propagates to stream_outputs() finally-block → abort_request() → abort_prefill().
Source code in vllm_mlx/server.py
4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 | |
vllm_mlx.server._wait_with_disconnect
async
¶
_wait_with_disconnect(coro, raw_request: Request, timeout: float, poll_interval: float = 0.5, timeout_detail_seconds: float | None = None, cleanup_result=None)
Run a coroutine with both timeout and client disconnect detection.
For non-streaming requests where _disconnect_guard() can't be used. Races the coroutine against a disconnect poller, same pattern as _disconnect_guard but for awaitable (non-generator) coroutines.
Source code in vllm_mlx/server.py
4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 | |
vllm_mlx.server._start_request_budget
¶
Return the total timeout and absolute deadline for a request.
vllm_mlx.server._remaining_request_timeout
¶
Compute remaining request budget or raise the standard timeout error.
Source code in vllm_mlx/server.py
vllm_mlx.server._acquire_default_engine_for_request
async
¶
_acquire_default_engine_for_request(raw_request: Request, *, total_timeout: float, deadline: float, count_activity: bool = True, model: str | None = None) -> BaseEngine | None
Acquire the engine for a request, using the model registry when active.
When _model_manager is set (registry mode), acquires the engine for the
requested model via _acquire_request_model. The resulting
RequestModelContext is stashed in _active_request_contexts keyed by
id(raw_request) so that the matching _release_default_engine call
can release the lease.
In single-model mode the behaviour is unchanged.
Source code in vllm_mlx/server.py
vllm_mlx.server._release_engine_for_request
async
¶
Release the engine acquired for this request.
In registry mode, releases the model lease stashed by
_acquire_default_engine_for_request. In single-model mode, falls
through to the default release path. count_activity must match the
flag used on the matching acquire so idle-unload accounting stays correct.
Source code in vllm_mlx/server.py
vllm_mlx.server._make_release_cleanup
¶
Return a cleanup callable suitable for _disconnect_guard.
Source code in vllm_mlx/server.py
vllm_mlx.server.create_completion
async
¶
create_completion(request: CompletionRequest, raw_request: Request)
Create a text completion.
Source code in vllm_mlx/server.py
4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 | |
vllm_mlx.server.create_chat_completion
async
¶
create_chat_completion(request: ChatCompletionRequest, raw_request: Request)
Create a chat completion (supports multimodal content for VLM models).
OpenAI-compatible multimodal format for images:
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{"type": "image_url", "image_url": {"url": "https://..."}}
]
}]
Video support:
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What happens in this video?"},
{"type": "video_url", "video_url": {"url": "https://example.com/video.mp4"}}
]
}]
Structured output (JSON mode):
Structured output (JSON Schema):
response_format={
"type": "json_schema",
"json_schema": {
"name": "my_schema",
"schema": {"type": "object", "properties": {...}}
}
}
Source code in vllm_mlx/server.py
4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 | |
vllm_mlx.server._normalize_messages
¶
Normalize message roles and merge consecutive same-role messages.
- Maps non-standard roles to standard ones (e.g.
developer->system). - Merges consecutive same-role messages to satisfy chat template constraints (Qwen 3.5, Llama, etc. require alternating roles).
Only merges when both messages have string content. Messages with list content (multimodal) are left as-is to preserve image/video attachments.
Parameters:
-
messages(list[dict]) –List of message dicts with 'role' and 'content' keys.
Returns:
-
list[dict]–New list with normalized roles and consecutive same-role messages merged.
Source code in vllm_mlx/server.py
vllm_mlx.server.create_response
async
¶
create_response(request: ResponsesRequest, raw_request: Request)
Create a Responses API response.
Source code in vllm_mlx/server.py
vllm_mlx.server._get_forced_tool_name
¶
Extract forced tool name from tool_choice, if any.
Returns the function name when tool_choice is a dict like {"type": "function", "function": {"name": "X"}}, or None otherwise.
Source code in vllm_mlx/server.py
vllm_mlx.server._apply_forced_tool_choice
¶
Apply forced tool_choice by filtering tools and injecting instructions.
Handles: - tool_choice={"type":"function","function":{"name":"X"}} -> filter + instruct - tool_choice="required" -> instruct model to call at least one tool
Parameters:
-
tool_choice–The tool_choice value from the request
-
tools–List of converted tools for the template
-
messages–The message list (will be copied if modified)
-
chat_kwargs–Optional dict to modify (e.g. disable thinking)
Returns:
-
–
Tuple of (tools, messages) - potentially filtered/modified
Source code in vllm_mlx/server.py
vllm_mlx.server._tool_name
¶
Extract function name from a tool definition dict.
vllm_mlx.server._inject_json_instruction
¶
Inject JSON instruction into messages.
If a system message exists, append to it. Otherwise, prepend a new system message.
Source code in vllm_mlx/server.py
vllm_mlx.server._convert_anthropic_stop_reason
¶
Convert OpenAI finish_reason to Anthropic stop_reason.
Source code in vllm_mlx/server.py
vllm_mlx.server._prepare_anthropic_endpoint_invocation
¶
_prepare_anthropic_endpoint_invocation(engine: BaseEngine, openai_request: ChatCompletionRequest, effective_max_tokens: int) -> PreparedChatInvocation
Prepare Anthropic invocation and convert URL-safety errors to 400s.
Source code in vllm_mlx/server.py
vllm_mlx.server.create_anthropic_message
async
¶
Anthropic Messages API endpoint.
Translates Anthropic-format requests to OpenAI format, runs inference through the existing engine, and converts the response back.
Supports both streaming and non-streaming modes.
Source code in vllm_mlx/server.py
5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 | |
vllm_mlx.server.count_anthropic_tokens
async
¶
Count tokens for an Anthropic Messages API request.
Uses the model's tokenizer for accurate counting. Claude Code calls this endpoint for token budgeting. Note: Don't parse via AnthropicRequest — count_tokens requests from Claude Code don't include max_tokens.
Source code in vllm_mlx/server.py
5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 | |
vllm_mlx.server._emit_content_pieces
¶
_emit_content_pieces(pieces: list[tuple[str, str]], current_block_type: str | None, block_index: int) -> tuple[list[str], str | None, int]
Emit Anthropic SSE events for content pieces from the think router.
Handles block type transitions (thinking <-> text), emitting content_block_start/stop/delta events as needed.
Parameters:
-
pieces(list[tuple[str, str]]) –List of (block_type, text) from StreamingThinkRouter
-
current_block_type(str | None) –Current open block type, or None
-
block_index(int) –Current block index
Returns:
-
tuple[list[str], str | None, int]–Tuple of (events, updated_block_type, updated_block_index)
Source code in vllm_mlx/server.py
vllm_mlx.server._stream_anthropic_messages
async
¶
_stream_anthropic_messages(engine: BaseEngine, openai_request: ChatCompletionRequest, anthropic_request: AnthropicRequest, prepared: PreparedChatInvocation, metrics_tracker=None) -> AsyncIterator[str]
Stream Anthropic Messages API SSE events.
Converts OpenAI streaming chunks to Anthropic event format: message_start -> content_block_start -> content_block_delta* -> content_block_stop -> message_delta -> message_stop
When a reasoning parser is active, emits a thinking content block
(index 0) for reasoning tokens and a text content block (index 1)
for the actual response, matching the Anthropic extended thinking format.
Source code in vllm_mlx/server.py
5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 | |
vllm_mlx.server.stream_completion
async
¶
stream_completion(engine: BaseEngine, prompt: str, request: CompletionRequest, max_tokens: int, repetition_penalty: float | None = None, metrics_tracker=None) -> AsyncIterator[str]
Stream completion response.
Source code in vllm_mlx/server.py
6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 | |
vllm_mlx.server.stream_chat_completion
async
¶
stream_chat_completion(engine: BaseEngine, messages: list, request: ChatCompletionRequest, metrics_tracker=None, **kwargs) -> AsyncIterator[str]
Stream chat completion response.
Source code in vllm_mlx/server.py
6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 | |
vllm_mlx.server.init_mcp
async
¶
Initialize MCP manager from config file.
Source code in vllm_mlx/server.py
vllm_mlx.server._make_keepalive_http_protocol
¶
Create a uvicorn HTTP protocol class with aggressive TCP keepalive.
When a client abruptly disconnects (power-off, network loss), the server
TCP stack won't notice for ~2 hours (default keepalive). With aggressive
keepalive (idle=10s, interval=5s, count=3), dead connections are detected
in ~25 seconds, letting _wait_with_disconnect() abort the request and
stop wasting GPU cycles on tokens nobody will receive.
Source code in vllm_mlx/server.py
vllm_mlx.server.main
¶
Run the server.
Source code in vllm_mlx/server.py
6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 | |
vllm_mlx.server.create_parser
¶
Create the standalone server CLI parser.
Source code in vllm_mlx/server.py
6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 | |
Complete contract reference¶
Expand any definition for its exact inputs, annotations, defaults, return contract, directly raised exceptions, source-grounded behavior, and immutable line link. This section includes private and nested definitions that ordinary API generators omit.
vllm_mlx.server._resolve_temperature · function
Resolve temperature: request > CLI default > fallback.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_value |
float \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
float - Direct return expressions:
request_value;_default_temperature;_FALLBACK_TEMPERATURE
Exceptions and behavior
Function _resolve_temperature has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._resolve_top_p · function
Resolve top_p: request > CLI default > fallback.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_value |
float \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
float - Direct return expressions:
request_value;_default_top_p;_FALLBACK_TOP_P
Exceptions and behavior
Function _resolve_top_p has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._resolve_top_k · function
Resolve top_k: request > CLI default > fallback.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_value |
int \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
int - Direct return expressions:
request_value;_default_top_k;_FALLBACK_TOP_K
Exceptions and behavior
Function _resolve_top_k has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._resolve_min_p · function
Resolve min_p: request > CLI default > fallback.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_value |
float \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
float - Direct return expressions:
request_value;_default_min_p;_FALLBACK_MIN_P
Exceptions and behavior
Function _resolve_min_p has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._resolve_presence_penalty · function
Resolve presence_penalty: request > CLI default > fallback.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_value |
float \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
float - Direct return expressions:
request_value;_default_presence_penalty;_FALLBACK_PRESENCE_PENALTY
Exceptions and behavior
Function _resolve_presence_penalty has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._resolve_repetition_penalty · function
Resolve repetition_penalty: request > CLI default > fallback.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_value |
float \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
float - Direct return expressions:
request_value;_default_repetition_penalty;_FALLBACK_REPETITION_PENALTY
Exceptions and behavior
Function _resolve_repetition_penalty has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._resolve_request_max_tokens · function
Resolve and validate a request's max_tokens budget.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
requested_value |
int \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
int - Direct return expressions:
_default_max_tokens;requested_value
Exceptions and behavior
Function _resolve_request_max_tokens calls HTTPException; can raise HTTPException; has 2 explicit return paths.
Directly raised exceptions: HTTPException.
vllm_mlx.server._resolve_chat_template_kwargs · function
vllm_mlx.server._resolve_chat_template_kwargs(request_value: dict[str, object] | None) -> dict[str, object]
Resolve chat template kwargs: request > server default > empty dict.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_value |
dict[str, object] \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
dict[str, object] - Direct return expressions:
resolved
Exceptions and behavior
Function _resolve_chat_template_kwargs calls resolved.update; returns resolved.
No direct raise statement appears in this definition.
vllm_mlx.server.PreparedChatInvocation · class
vllm_mlx.server.PreparedChatInvocation(messages: list[dict], chat_kwargs: dict[str, object], response_format: object | None, json_logits_processor: object | None, thinking_processor: object | None = None)
Fully prepared inputs for a single engine.chat/stream_chat call.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
messages |
list[dict] |
yes |
none |
Required constructor field. |
chat_kwargs |
dict[str, object] |
yes |
none |
Required constructor field. |
response_format |
object \| None |
yes |
none |
Required constructor field. |
json_logits_processor |
object \| None |
yes |
none |
Required constructor field. |
thinking_processor |
object \| None |
no |
None |
Optional constructor field; defaults to None. |
Returns
- Constructs:
vllm_mlx.server.PreparedChatInvocation
Exceptions and behavior
Class PreparedChatInvocation declares 0 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.server._prepare_chat_messages · function
vllm_mlx.server._prepare_chat_messages(engine: BaseEngine, request_messages: list[Message | dict]) -> tuple[list[dict], list, list, list, bool]
Normalize messages and collect media once for both stream/non-stream paths.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
request_messages |
list[Message \| dict] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[list[dict], list, list, list, bool] - Direct return expressions:
(messages, images, videos, audios, has_media)
Exceptions and behavior
Function _prepare_chat_messages calls _validate_remote_media_urls, bool, getattr, hasattr; returns (messages, images, videos, audios, has_media).
No direct raise statement appears in this definition.
vllm_mlx.server._iter_remote_media_urls · function
Yield remote media URLs from OpenAI-style multimodal message content.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
messages |
list[Message \| dict] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Yields values incrementally.
Exceptions and behavior
Function _iter_remote_media_urls calls isinstance, msg.get, hasattr, item.model_dump; yields values incrementally.
No direct raise statement appears in this definition.
vllm_mlx.server._validate_remote_media_urls · function
Validate remote media URLs during request preparation.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
messages |
list[Message \| dict] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Function _validate_remote_media_urls calls _iter_remote_media_urls, _validate_url_safety.
No direct raise statement appears in this definition.
vllm_mlx.server._raise_remote_media_http_error · function
Log internal URL-safety detail while returning a generic client error.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
exc |
UnsafeRemoteURLError |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Function _raise_remote_media_http_error calls logger.warning, _sanitize_log_text, HTTPException; can raise HTTPException.
Directly raised exceptions: HTTPException.
vllm_mlx.server._prepare_json_logits_processor · function
vllm_mlx.server._prepare_json_logits_processor(engine: BaseEngine, messages: list[dict], response_format: object | None, *, tools: list | None, tool_choice: object | None, log_context: str | None = None, thinking_model: bool = False) -> tuple[list[dict], object | None]
Inject response_format instruction and build constrained decoding processor.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
messages |
list[dict] |
yes |
none |
Required positional or keyword input. |
response_format |
object \| None |
yes |
none |
Required positional or keyword input. |
tools |
list \| None |
yes |
none |
Required keyword-only input. |
tool_choice |
object \| None |
yes |
none |
Required keyword-only input. |
log_context |
str \| None |
no |
None |
Optional keyword-only input; defaults to None. |
thinking_model |
bool |
no |
False |
Optional keyword-only input; defaults to False. |
Returns
- Type:
tuple[list[dict], object | None] - Direct return expressions:
(messages, json_logits_processor)
Exceptions and behavior
Function _prepare_json_logits_processor calls build_json_system_prompt, _inject_json_instruction, _get_engine_tokenizer, build_json_logits_processor; returns (messages, json_logits_processor).
No direct raise statement appears in this definition.
vllm_mlx.server._build_thinking_processor · function
vllm_mlx.server._build_thinking_processor(engine: BaseEngine, thinking_token_budget: int, *, inner: object | None = None, prompt_has_think_tag: bool = True) -> object | None
Build a ThinkingAwareLogitsProcessor if the tokenizer has think tokens.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
thinking_token_budget |
int |
yes |
none |
Required positional or keyword input. |
inner |
object \| None |
no |
None |
Optional keyword-only input; defaults to None. |
prompt_has_think_tag |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
Returns
- Type:
object | None - Direct return expressions:
None;proc
Exceptions and behavior
Function _build_thinking_processor calls _get_engine_tokenizer, tokenizer.encode, logger.debug, getattr; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._resolve_no_final_content_token_limit · function
Function _resolve_no_final_content_token_limit calls os.environ.get, raw.strip, int, logger.warning; has 2 explicit return paths.
Parameters
This callable has no explicit inputs.
Returns
- Type:
int | None - Direct return expressions:
None;value
Exceptions and behavior
Function _resolve_no_final_content_token_limit calls os.environ.get, raw.strip, int, logger.warning; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._generation_metadata · function
vllm_mlx.server._generation_metadata(thinking_processor: object | None) -> GenerationMetadata | None
Function _generation_metadata calls GenerationMetadata, getattr, bool; has 2 explicit return paths.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
thinking_processor |
object \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
GenerationMetadata | None - Direct return expressions:
None;GenerationMetadata(no_final_content_watchdog_tokens=getattr(thinking_processor, '_no_final_content_token_limit', None),…
Exceptions and behavior
Function _generation_metadata calls GenerationMetadata, getattr, bool; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._ThinkingAwareLogitsProcessor · class
Wrap a JSONSchemaLogitsProcessor so JSON constraining only activates after the model emits </think>, letting it reason freely first.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
inner |
not annotated |
yes |
none |
Required positional or keyword input. |
prompt_has_think_tag |
bool |
no |
False |
Optional positional or keyword input; defaults to False. |
Returns
- Constructs:
vllm_mlx.server._ThinkingAwareLogitsProcessor
Exceptions and behavior
Class _ThinkingAwareLogitsProcessor declares 5 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.server._ThinkingAwareLogitsProcessor.__init__ · method
vllm_mlx.server._ThinkingAwareLogitsProcessor.__init__(inner, prompt_has_think_tag: bool = False) -> not annotated
Method _ThinkingAwareLogitsProcessor.__init__ updates self._inner, self._active, self._in_thinking, self._waiting_for_json.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
inner |
not annotated |
yes |
none |
Required positional or keyword input. |
prompt_has_think_tag |
bool |
no |
False |
Optional positional or keyword input; defaults to False. |
Returns
- Type:
not annotated
Exceptions and behavior
Method _ThinkingAwareLogitsProcessor.__init__ updates self._inner, self._active, self._in_thinking, self._waiting_for_json.
No direct raise statement appears in this definition.
vllm_mlx.server._ThinkingAwareLogitsProcessor._scan_for_json_start · method
vllm_mlx.server._ThinkingAwareLogitsProcessor._scan_for_json_start(tokens_list, tokens, logits) -> not annotated
Scan generated tokens for the first { or [.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens_list |
not annotated |
yes |
none |
Required positional or keyword input. |
tokens |
not annotated |
yes |
none |
Required positional or keyword input. |
logits |
not annotated |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
self._inner(tokens, logits);logits
Exceptions and behavior
Method _ThinkingAwareLogitsProcessor._scan_for_json_start updates self._active, self._inner._prompt_len; calls len, range, self._tokenizer.decode, any; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._ThinkingAwareLogitsProcessor.__call__ · method
Method _ThinkingAwareLogitsProcessor.__call__ updates self._base_prompt_len, self._in_thinking, self._waiting_for_json, self._json_scan_offset; calls self._inner, hasattr, tokens.tolist, list; has 3 explicit return paths.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
not annotated |
yes |
none |
Required positional or keyword input. |
logits |
not annotated |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
self._inner(tokens, logits);self._scan_for_json_start(tokens_list, tokens, logits);logits
Exceptions and behavior
Method _ThinkingAwareLogitsProcessor.__call__ updates self._base_prompt_len, self._in_thinking, self._waiting_for_json, self._json_scan_offset; calls self._inner, hasattr, tokens.tolist, list; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._ThinkingAwareLogitsProcessor.schema · method
Method _ThinkingAwareLogitsProcessor.schema returns self._inner.schema.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
self._inner.schema
Exceptions and behavior
Method _ThinkingAwareLogitsProcessor.schema returns self._inner.schema.
No direct raise statement appears in this definition.
vllm_mlx.server._ThinkingAwareLogitsProcessor._disabled · method
Method _ThinkingAwareLogitsProcessor._disabled returns self._inner._disabled.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
self._inner._disabled
Exceptions and behavior
Method _ThinkingAwareLogitsProcessor._disabled returns self._inner._disabled.
No direct raise statement appears in this definition.
vllm_mlx.server._attach_response_format_logits_processor · function
vllm_mlx.server._attach_response_format_logits_processor(chat_kwargs: dict, json_logits_processor: object) -> object
Attach response_format constraints and keep thinking disabled.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
chat_kwargs |
dict |
yes |
none |
Required positional or keyword input. |
json_logits_processor |
object |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
object - Direct return expressions:
json_logits_processor
Exceptions and behavior
Function _attach_response_format_logits_processor calls dict, chat_kwargs.get, list; returns json_logits_processor.
No direct raise statement appears in this definition.
vllm_mlx.server._coerce_logit_bias · function
Function _coerce_logit_bias calls logit_bias.items, int, float, HTTPException; can raise HTTPException; returns coerced.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
logit_bias |
dict[str, float] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
dict[int, float] - Direct return expressions:
coerced
Exceptions and behavior
Function _coerce_logit_bias calls logit_bias.items, int, float, HTTPException; can raise HTTPException; returns coerced.
Directly raised exceptions: HTTPException.
vllm_mlx.server._attach_logit_bias_processor · function
vllm_mlx.server._attach_logit_bias_processor(chat_kwargs: dict, logit_bias: dict[str, float] | None) -> not annotated
Function _attach_logit_bias_processor calls make_logits_processors, _coerce_logit_bias, chat_kwargs.get, list; returns None.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
chat_kwargs |
dict |
yes |
none |
Required positional or keyword input. |
logit_bias |
dict[str, float] \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
None
Exceptions and behavior
Function _attach_logit_bias_processor calls make_logits_processors, _coerce_logit_bias, chat_kwargs.get, list; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server._prepare_chat_completion_invocation · function
vllm_mlx.server._prepare_chat_completion_invocation(engine: BaseEngine, request: ChatCompletionRequest, effective_max_tokens: int) -> PreparedChatInvocation
Precompute messages, kwargs, and decoding constraints for chat completions.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
effective_max_tokens |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
PreparedChatInvocation - Direct return expressions:
PreparedChatInvocation(messages=messages, chat_kwargs=chat_kwargs, response_format=response_format, json_logits_process…
Exceptions and behavior
Function _prepare_chat_completion_invocation calls _prepare_chat_messages, _prepare_json_logits_processor, bool, _resolve_temperature; returns PreparedChatInvocation(messages=messages, chat_kwargs=chat_kwargs, response_format=response_format, json_logits_process….
No direct raise statement appears in this definition.
vllm_mlx.server._prepare_anthropic_invocation · function
vllm_mlx.server._prepare_anthropic_invocation(engine: BaseEngine, openai_request: ChatCompletionRequest, effective_max_tokens: int) -> PreparedChatInvocation
Precompute messages, kwargs, and decoding constraints for Anthropic API.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
openai_request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
effective_max_tokens |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
PreparedChatInvocation - Direct return expressions:
PreparedChatInvocation(messages=messages, chat_kwargs=chat_kwargs, response_format=response_format, json_logits_process…
Exceptions and behavior
Function _prepare_anthropic_invocation calls _prepare_chat_messages, _prepare_json_logits_processor, bool, _resolve_temperature; returns PreparedChatInvocation(messages=messages, chat_kwargs=chat_kwargs, response_format=response_format, json_logits_process….
No direct raise statement appears in this definition.
vllm_mlx.server._thinking_disabled · function
Return True iff thinking is explicitly disabled for this request.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
not annotated |
yes |
none |
Required positional or keyword input. |
chat_kwargs |
dict \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
bool - Direct return expressions:
True;False
Exceptions and behavior
Function _thinking_disabled calls getattr, chat_kwargs.get, ctk.get; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._strip_backslash_before_unicode · function
Remove spurious backslashes before non-ASCII chars in JSON string values.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
obj |
object |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
object - Direct return expressions:
{k: _strip_backslash_before_unicode(v) for k, v in obj.items()};[_strip_backslash_before_unicode(v) for v in obj];re.sub('\\\\([^\\x00-\\x7F])', '\\1', obj);obj
Exceptions and behavior
Function _strip_backslash_before_unicode calls isinstance, _strip_backslash_before_unicode, obj.items, re.sub; has 4 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._sanitize_log_text · function
Escape control characters before logging untrusted text.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
value |
object |
yes |
none |
Required positional or keyword input. |
limit |
int \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
str - Direct return expressions:
sanitized[:limit] + '...';sanitized
Exceptions and behavior
Function _sanitize_log_text calls str, escaped.append, ch.isprintable, ord; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._log_and_raise_internal_error · function
Log a sanitized exception string and raise a generic 500 response.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
log_prefix |
str |
yes |
none |
Required positional or keyword input. |
exc |
Exception |
yes |
none |
Required positional or keyword input. |
detail |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Function _log_and_raise_internal_error calls logger.error, _sanitize_log_text, HTTPException; can raise HTTPException.
Directly raised exceptions: HTTPException.
vllm_mlx.server._raise_engine_busy · function
Translate serialized-engine admission failures into retryable HTTP 503.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
exc |
EngineBusy |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Function _raise_engine_busy calls HTTPException, str; can raise HTTPException.
Directly raised exceptions: HTTPException.
vllm_mlx.server.RequestModelContext · class
vllm_mlx.server.RequestModelContext(model_name: str, engine: BaseEngine, lease: ModelLease | None = None)
Request-scoped engine/lease context.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model_name |
str |
yes |
none |
Required constructor field. |
engine |
BaseEngine |
yes |
none |
Required constructor field. |
lease |
ModelLease \| None |
no |
None |
Optional constructor field; defaults to None. |
Returns
- Constructs:
vllm_mlx.server.RequestModelContext
Exceptions and behavior
Class RequestModelContext declares 1 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.server.RequestModelContext.release · method
Release the registry lease once, if this context owns one.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None
Exceptions and behavior
Method RequestModelContext.release updates self.lease; calls lease.release; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server._list_available_model_names · function
Function _list_available_model_names has 2 explicit return paths.
Parameters
This callable has no explicit inputs.
Returns
- Type:
list[str] - Direct return expressions:
_model_manager.registered_model_names;[_model_name] if _model_name else []
Exceptions and behavior
Function _list_available_model_names has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._response_model_name · function
Return the response model field for single-model or registry mode.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_model |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
_model_name or request_model
Exceptions and behavior
Function _response_model_name returns _model_name or request_model.
No direct raise statement appears in this definition.
vllm_mlx.server._acquire_request_model · function
Acquire the model/engine that should serve this request.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_model |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
RequestModelContext - Direct return expressions:
RequestModelContext(model_name=_model_name or request_model, engine=engine);RequestModelContext(model_name=request_model, engine=lease.engine, lease=lease)
Exceptions and behavior
Function _acquire_request_model calls _validate_model_name, get_engine, _detect_native_tool_support, _detect_harmony_rendering; awaits asynchronous work; can raise HTTPException; has 2 explicit return paths.
Directly raised exceptions: HTTPException.
vllm_mlx.server._stream_with_model_context · function
async vllm_mlx.server._stream_with_model_context(context: RequestModelContext, stream: AsyncIterator[str]) -> AsyncIterator[str]
Ensure model leases survive for the full streaming response.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
context |
RequestModelContext |
yes |
none |
Required positional or keyword input. |
stream |
AsyncIterator[str] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
AsyncIterator[str] - Yields values incrementally.
Exceptions and behavior
Function _stream_with_model_context calls context.release; awaits asynchronous work; yields values incrementally.
No direct raise statement appears in this definition.
vllm_mlx.server._build_tool_parser · function
Create a fresh tool parser instance for a single request/stream.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
None;parser_cls(tokenizer);parser_cls()
Exceptions and behavior
Function _build_tool_parser calls type, ToolParserManager.get_tool_parser, _get_engine_tokenizer, parser_cls; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._build_reasoning_parser · function
Create a fresh reasoning parser instance for a single request/stream.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
not annotated - Direct return expressions:
parser_cls(tokenizer);parser_cls();None;type(_reasoning_parser)(tokenizer);type(_reasoning_parser)()
Exceptions and behavior
Function _build_reasoning_parser calls getattr, get_reasoning_parser, parser_cls, type(_reasoning_parser); has 5 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._prepare_streaming_reasoning_parser · function
vllm_mlx.server._prepare_streaming_reasoning_parser(engine: BaseEngine, request: ChatCompletionRequest | ResponsesRequest | None, chat_kwargs: dict[str, object], *, allowed: bool = True) -> not annotated
Build and reset request-local reasoning state when thinking is enabled.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
request |
ChatCompletionRequest \| ResponsesRequest \| None |
yes |
none |
Required positional or keyword input. |
chat_kwargs |
dict[str, object] |
yes |
none |
Required positional or keyword input. |
allowed |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
Returns
- Type:
not annotated - Direct return expressions:
None;parser
Exceptions and behavior
Function _prepare_streaming_reasoning_parser calls _thinking_disabled, _build_reasoning_parser, parser.reset_state; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._prepare_openai_stream_reasoning_state · function
vllm_mlx.server._prepare_openai_stream_reasoning_state(engine: BaseEngine, request: ChatCompletionRequest, chat_kwargs: dict[str, object]) -> tuple[object | None, bool]
Return request-local reasoning state and the legacy Nemotron marker state.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
chat_kwargs |
dict[str, object] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[object | None, bool] - Direct return expressions:
(parser, is_thinking_model)
Exceptions and behavior
Function _prepare_openai_stream_reasoning_state calls _prepare_streaming_reasoning_parser, (engine.model_name or '').lower, _thinking_disabled; returns (parser, is_thinking_model).
No direct raise statement appears in this definition.
vllm_mlx.server._request_tool_definitions · function
Return the request tool schema once for streaming argument coercion.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list | None - Direct return expressions:
request.model_dump(include={'tools'}).get('tools');None
Exceptions and behavior
Function _request_tool_definitions calls request.model_dump(include={'tools'}).get, request.model_dump; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._streaming_json_fence_stripper · function
vllm_mlx.server._streaming_json_fence_stripper(request: ChatCompletionRequest) -> StreamingJsonFenceStripper | None
Create a fence stripper only for JSON-constrained streaming responses.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
StreamingJsonFenceStripper | None - Direct return expressions:
StreamingJsonFenceStripper();None
Exceptions and behavior
Function _streaming_json_fence_stripper calls getattr, isinstance, response_format.get, StreamingJsonFenceStripper; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._get_idle_unload_event · function
Return the idle-unload gate event, creating it on first use.
Parameters
This callable has no explicit inputs.
Returns
- Type:
asyncio.Event - Direct return expressions:
_idle_unload_enabled
Exceptions and behavior
Function _get_idle_unload_event calls asyncio.Event, _idle_unload_enabled.set; returns _idle_unload_enabled.
No direct raise statement appears in this definition.
vllm_mlx.server._invalidate_tool_parser_cache · function
Drop cached parser state when the serving tokenizer changes.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
reason |
str \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Function _invalidate_tool_parser_cache calls logger.debug; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server._load_prefix_cache_from_disk · function
Load prefix cache from disk during startup.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Function _load_prefix_cache_from_disk calls _get_cache_dir, logger.info, target_engine.load_cache_from_disk, logger.warning; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server._save_prefix_cache_to_disk · function
Save prefix cache to disk during shutdown.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Function _save_prefix_cache_to_disk calls _get_cache_dir, logger.info, target_engine.save_cache_to_disk, logger.warning; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server._get_cache_dir · function
Get cache persistence directory based on actual model path.
Parameters
This callable has no explicit inputs.
Returns
- Type:
str - Direct return expressions:
cache_dir
Exceptions and behavior
Function _get_cache_dir calls logger.info, type, str(model_name).replace('/', '--').replace, str(model_name).replace; returns cache_dir.
No direct raise statement appears in this definition.
vllm_mlx.server._build_engine · function
Construct an engine instance from a model spec without starting it.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
spec |
ModelSpec |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
BaseEngine - Direct return expressions:
BatchedEngine(model_name=spec.model_name, scheduler_config=spec.scheduler_config, stream_interval=spec.stream_interval,…;SimpleEngine(model_name=spec.model_name, force_mllm=spec.force_mllm, mtp=spec.mtp, prefill_step_size=spec.prefill_step_…
Exceptions and behavior
Function _build_engine calls logger.info, BatchedEngine, getattr, SimpleEngine; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._engine_factory · function
Async engine factory used by the residency manager.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
spec |
ModelSpec |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
BaseEngine - Direct return expressions:
_build_engine(spec)
Exceptions and behavior
Function _engine_factory calls _build_engine; returns _build_engine(spec).
No direct raise statement appears in this definition.
vllm_mlx.server._run_blocking_engine_cache_io · function
Run blocking cache persistence off the event loop.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
io_fn |
not annotated |
yes |
none |
Required positional or keyword input. |
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Function _run_blocking_engine_cache_io calls asyncio.create_task, asyncio.to_thread, asyncio.shield, suspend_cancellation; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server._restore_engine_state · function
Restore engine-local state, such as prefix cache, after a cold load.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
spec |
ModelSpec |
yes |
none |
Required positional or keyword input. |
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Function _restore_engine_state calls hasattr, _run_blocking_engine_cache_io; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server._persist_engine_state · function
Persist engine-local state before an idle unload or shutdown unload.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
spec |
ModelSpec |
yes |
none |
Required positional or keyword input. |
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Function _persist_engine_state calls hasattr, _run_blocking_engine_cache_io; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server._activate_engine · function
Set the global engine pointer and refresh parser-sensitive state.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
BaseEngine | None - Direct return expressions:
_engine
Exceptions and behavior
Function _activate_engine calls _invalidate_tool_parser_cache, _detect_native_tool_support, _detect_harmony_rendering; returns _engine.
No direct raise statement appears in this definition.
vllm_mlx.server._sync_engine_from_residency · function
Sync the global engine pointer from the residency manager state.
Parameters
This callable has no explicit inputs.
Returns
- Type:
BaseEngine | None - Direct return expressions:
_engine;_activate_engine(_residency_manager.get_engine(_default_model_key))
Exceptions and behavior
Function _sync_engine_from_residency calls _activate_engine, _residency_manager.get_engine; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._get_lifecycle_status · function
Get lifecycle status for the default resident if lifecycle is enabled.
Parameters
This callable has no explicit inputs.
Returns
- Type:
dict | None - Direct return expressions:
None;_residency_manager.get_status(_default_model_key)
Exceptions and behavior
Function _get_lifecycle_status calls _residency_manager.get_status; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._public_lifecycle_status · function
Return residency status safe for unauthenticated public endpoints.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
lifecycle |
dict \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
dict | None - Direct return expressions:
None;public
Exceptions and behavior
Function _public_lifecycle_status calls dict; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._lifecycle_loop · function
Background idle-unload loop for the default resident.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None
Exceptions and behavior
Function _lifecycle_loop calls asyncio.sleep, _get_idle_unload_event().wait, _get_idle_unload_event, _residency_manager.unload_if_idle; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server._acquire_default_engine · function
Acquire the default engine, auto-loading via the residency manager if needed.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
count_activity |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
Returns
- Type:
BaseEngine - Direct return expressions:
get_engine();activated_engine
Exceptions and behavior
Function _acquire_default_engine calls get_engine, _residency_manager.acquire, _activate_engine, HTTPException; awaits asynchronous work; can raise HTTPException; has 2 explicit return paths.
Directly raised exceptions: HTTPException.
vllm_mlx.server._release_default_engine · function
Release the default engine after request processing.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
count_activity |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Function _release_default_engine calls _residency_manager.release, _sync_engine_from_residency; awaits asynchronous work; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server.lifespan · function
FastAPI lifespan for startup/shutdown events.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
app |
FastAPI |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Yields values incrementally.
Exceptions and behavior
Function lifespan calls _get_idle_unload_event().clear, _get_idle_unload_event, _residency_manager.ensure_loaded, _sync_engine_from_residency; awaits asynchronous work; yields values incrementally; can raise primary_exc, cleanup_exc.
Directly raised exceptions: primary_exc, cleanup_exc.
vllm_mlx.server._metrics_result_from_status · function
Map HTTP-ish status codes to low-cardinality inference results.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
status_code |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
'client_closed';'timeout';'error';'success'
Exceptions and behavior
Function _metrics_result_from_status has 4 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._metrics_path_for_request · function
Prefer route templates over raw URLs to keep metrics cardinality bounded.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
Request |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
str(path);'__unmatched__'
Exceptions and behavior
Function _metrics_path_for_request calls request.scope.get, getattr, str, candidate.matches; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._metrics_middleware · function
Capture generic HTTP request metrics when enabled.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
Request |
yes |
none |
Required positional or keyword input. |
call_next |
not annotated |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
await call_next(request);response
Exceptions and behavior
Function _metrics_middleware calls call_next, _metrics_path_for_request, time.perf_counter, _metrics.observe_http_start; awaits asynchronous work; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.RateLimiter · class
Simple in-memory rate limiter using sliding window.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
requests_per_minute |
int |
no |
60 |
Optional positional or keyword input; defaults to 60. |
enabled |
bool |
no |
False |
Optional positional or keyword input; defaults to False. |
Returns
- Constructs:
vllm_mlx.server.RateLimiter
Exceptions and behavior
Class RateLimiter declares 2 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.server.RateLimiter.__init__ · method
vllm_mlx.server.RateLimiter.__init__(requests_per_minute: int = 60, enabled: bool = False) -> not annotated
Method RateLimiter.__init__ updates self.requests_per_minute, self.enabled, self.window_size, self._requests; calls defaultdict, threading.Lock.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
requests_per_minute |
int |
no |
60 |
Optional positional or keyword input; defaults to 60. |
enabled |
bool |
no |
False |
Optional positional or keyword input; defaults to False. |
Returns
- Type:
not annotated
Exceptions and behavior
Method RateLimiter.__init__ updates self.requests_per_minute, self.enabled, self.window_size, self._requests; calls defaultdict, threading.Lock.
No direct raise statement appears in this definition.
vllm_mlx.server.RateLimiter.is_allowed · method
Check if request is allowed for client.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
client_id |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[bool, int] - Direct return expressions:
(True, 0);(False, max(1, retry_after))
Exceptions and behavior
Method RateLimiter.is_allowed calls time.time, len, min, int; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.check_rate_limit · function
Rate limiting dependency.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
Request |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated
Exceptions and behavior
Function check_rate_limit calls request.headers.get, _rate_limiter.is_allowed, HTTPException, str; can raise HTTPException.
Directly raised exceptions: HTTPException.
vllm_mlx.server.verify_api_key · function
async vllm_mlx.server.verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)) -> not annotated
Verify API key if authentication is enabled.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
credentials |
HTTPAuthorizationCredentials |
no |
Depends(security) |
Optional positional or keyword input; defaults to Depends(security). |
Returns
- Type:
not annotated - Direct return expressions:
True
Exceptions and behavior
Function verify_api_key calls logger.warning, HTTPException, secrets.compare_digest; can raise HTTPException; returns True.
Directly raised exceptions: HTTPException.
vllm_mlx.server.get_engine · function
Get the loaded engine, raising error if not loaded.
Parameters
This callable has no explicit inputs.
Returns
- Type:
BaseEngine - Direct return expressions:
_engine
Exceptions and behavior
Function get_engine calls HTTPException; can raise HTTPException; returns _engine.
Directly raised exceptions: HTTPException.
vllm_mlx.server._coerce_tool_arguments · function
vllm_mlx.server._coerce_tool_arguments(arguments_json: str, tool_name: str, tools: list[dict] | None) -> str
Coerce tool call arguments to match the tool schema.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
arguments_json |
str |
yes |
none |
Required positional or keyword input. |
tool_name |
str |
yes |
none |
Required positional or keyword input. |
tools |
list[dict] \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
arguments_json;json.dumps(arguments, ensure_ascii=False)
Exceptions and behavior
Function _coerce_tool_arguments calls isinstance, tool.get('function', {}).get, tool.get, tool['function'].get; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._validate_model_name · function
Validate that the request model name matches the served model.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_model |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Function _validate_model_name calls _model_manager.has_model, ', '.join, _list_available_model_names, HTTPException; can raise HTTPException; returns None.
Directly raised exceptions: HTTPException.
vllm_mlx.server._get_engine_tokenizer · function
Return tokenizer-like parser state from the active engine.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
object | None - Direct return expressions:
None;tokenizer;getattr(engine, '_tokenizer', None)
Exceptions and behavior
Function _get_engine_tokenizer calls getattr; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._get_or_init_tool_parser · function
Return the cached tool parser, initializing it from the given engine.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
not annotated - Direct return expressions:
_tool_parser_instance
Exceptions and behavior
Function _get_or_init_tool_parser calls ToolParserManager.get_tool_parser, _get_engine_tokenizer, parser_cls, logger.info; returns _tool_parser_instance.
No direct raise statement appears in this definition.
vllm_mlx.server._parse_tool_calls_with_parser · function
vllm_mlx.server._parse_tool_calls_with_parser(output_text: str, request: ChatCompletionRequest | None = None, engine: BaseEngine | None = None) -> tuple[str, list | None]
Parse tool calls from model output using the configured parser.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
output_text |
str |
yes |
none |
The model output text |
request |
ChatCompletionRequest \| None |
no |
None |
The original request (for context) |
engine |
BaseEngine \| None |
no |
None |
The request-local engine to use for parser initialization |
Returns
- Type:
tuple[str, list | None] - Direct return expressions:
(output_text, None);parse_tool_calls(output_text, request_dict);(result.content or '', tool_calls);(fallback_text, fallback_calls);(result.content, None);(fallback_text, None)
Exceptions and behavior
Function _parse_tool_calls_with_parser calls request.model_dump, getattr, request_dict.get, parse_tool_calls; has 6 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._apply_response_format_or_raise · function
vllm_mlx.server._apply_response_format_or_raise(text: str, response_format: object, *, ensure_ascii: bool = False) -> str
Return validated JSON content or fail before returning a success response.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
text |
str |
yes |
none |
Required positional or keyword input. |
response_format |
object |
yes |
none |
Required positional or keyword input. |
ensure_ascii |
bool |
no |
False |
Optional keyword-only input; defaults to False. |
Returns
- Type:
str - Direct return expressions:
_strip_backslash_before_unicode(text)
Exceptions and behavior
Function _apply_response_format_or_raise calls apply_response_format_or_error, HTTPException, _strip_backslash_before_unicode; can raise HTTPException; returns _strip_backslash_before_unicode(text).
Directly raised exceptions: HTTPException.
vllm_mlx.server._response_format_type · function
Function _response_format_type calls isinstance, response_format.get, getattr; has 3 explicit return paths.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
response_format |
object \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str | None - Direct return expressions:
None;response_format.get('type');getattr(response_format, 'type', None)
Exceptions and behavior
Function _response_format_type calls isinstance, response_format.get, getattr; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._promote_streaming_response_format_delta · function
vllm_mlx.server._promote_streaming_response_format_delta(content: str | None, reasoning: str | None, request: ChatCompletionRequest) -> tuple[str | None, str | None]
Keep response_format JSON on the streaming content channel.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
content |
str \| None |
yes |
none |
Required positional or keyword input. |
reasoning |
str \| None |
yes |
none |
Required positional or keyword input. |
request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[str | None, str | None] - Direct return expressions:
(content, reasoning);(reasoning, None)
Exceptions and behavior
Function _promote_streaming_response_format_delta calls _response_format_type, getattr; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._new_response_item_id · function
Generate stable OpenAI-style item ids.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
prefix |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
f'{prefix}_{uuid.uuid4().hex}'
Exceptions and behavior
Function _new_response_item_id calls uuid.uuid4; returns f'{prefix}_{uuid.uuid4().hex}'.
No direct raise statement appears in this definition.
vllm_mlx.server._response_content_to_text · function
Normalize Responses API content items into plain text.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
content |
not annotated |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
'';content;'\n'.join((part for part in text_parts if part))
Exceptions and behavior
Function _response_content_to_text calls isinstance, part.get, getattr, text_parts.append; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._responses_tools_to_chat_tools · function
vllm_mlx.server._responses_tools_to_chat_tools(tools: list[ResponseFunctionTool | dict]) -> tuple[list[dict] | None, list[str]]
Convert supported Responses tools and report unsupported tool types.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tools |
list[ResponseFunctionTool \| dict] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[list[dict] | None, list[str]] - Direct return expressions:
(None, []);(supported or None, unsupported)
Exceptions and behavior
Function _responses_tools_to_chat_tools calls isinstance, tool.get, unsupported.append, type; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._responses_input_to_chat_messages · function
Convert Responses API input items into chat-completions-style messages.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[dict] - Direct return expressions:
messages
Exceptions and behavior
Function _responses_input_to_chat_messages calls _responses_store.get, HTTPException, messages.extend, copy.deepcopy; can raise HTTPException; returns messages.
Directly raised exceptions: HTTPException.
vllm_mlx.server._responses_request_to_new_persisted_messages · function
vllm_mlx.server._responses_request_to_new_persisted_messages(request: ResponsesRequest) -> list[dict]
Persist only the current request's replayable input items.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[dict] - Direct return expressions:
_responses_input_to_chat_messages(request_without_history)
Exceptions and behavior
Function _responses_request_to_new_persisted_messages calls request.model_copy, _responses_input_to_chat_messages; returns _responses_input_to_chat_messages(request_without_history).
No direct raise statement appears in this definition.
vllm_mlx.server._responses_request_to_persisted_messages · function
Persist replayable history for chained previous_response_id requests.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[dict] - Direct return expressions:
messages
Exceptions and behavior
Function _responses_request_to_persisted_messages calls _responses_store.get, HTTPException, messages.extend, copy.deepcopy; can raise HTTPException; returns messages.
Directly raised exceptions: HTTPException.
vllm_mlx.server._responses_request_to_chat_request · function
vllm_mlx.server._responses_request_to_chat_request(request: ResponsesRequest) -> ChatCompletionRequest
Build a ChatCompletionRequest from a ResponsesRequest.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
ChatCompletionRequest - Direct return expressions:
ChatCompletionRequest(model=request.model, messages=[Message(**msg) for msg in messages], temperature=request.temperatu…
Exceptions and behavior
Function _responses_request_to_chat_request calls HTTPException, logger.debug, _responses_tools_to_chat_tools, _responses_input_to_chat_messages; can raise HTTPException; returns ChatCompletionRequest(model=request.model, messages=[Message(**msg) for msg in messages], temperature=request.temperatu….
Directly raised exceptions: HTTPException.
vllm_mlx.server._build_responses_output_items · function
vllm_mlx.server._build_responses_output_items(text: str | None, reasoning: str | None, tool_calls: list[ToolCall] | None) -> list[ResponseMessageItem | ResponseReasoningItem | ResponseFunctionCallItem]
Convert parsed assistant output into Responses API output items.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
text |
str \| None |
yes |
none |
Required positional or keyword input. |
reasoning |
str \| None |
yes |
none |
Required positional or keyword input. |
tool_calls |
list[ToolCall] \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[ResponseMessageItem | ResponseReasoningItem | ResponseFunctionCallItem] - Direct return expressions:
output_items
Exceptions and behavior
Function _build_responses_output_items calls output_items.append, ResponseReasoningItem, _new_response_item_id, ResponseReasoningTextPart; returns output_items.
No direct raise statement appears in this definition.
vllm_mlx.server._response_output_items_to_chat_messages · function
Persist assistant output in chat-completions form for previous_response_id.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
output_items |
list |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[dict] - Direct return expressions:
[];[{'role': 'assistant', 'content': ''.join(assistant_text_parts), 'tool_calls': assistant_tool_calls or None}]
Exceptions and behavior
Function _response_output_items_to_chat_messages calls isinstance, assistant_text_parts.append, _response_content_to_text, assistant_tool_calls.append; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._build_response_object · function
vllm_mlx.server._build_response_object(request: ResponsesRequest, output_items: list[ResponseMessageItem | ResponseReasoningItem | ResponseFunctionCallItem], prompt_tokens: int, completion_tokens: int, finish_reason: str | None, response_id: str | None = None) -> ResponseObject
Build a full Responses API object.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
output_items |
list[ResponseMessageItem \| ResponseReasoningItem \| ResponseFunctionCallItem] |
yes |
none |
Required positional or keyword input. |
prompt_tokens |
int |
yes |
none |
Required positional or keyword input. |
completion_tokens |
int |
yes |
none |
Required positional or keyword input. |
finish_reason |
str \| None |
yes |
none |
Required positional or keyword input. |
response_id |
str \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
ResponseObject - Direct return expressions:
response
Exceptions and behavior
Function _build_response_object calls ResponseObject, _new_response_item_id, _resolve_top_p, _resolve_temperature; returns response.
No direct raise statement appears in this definition.
vllm_mlx.server._prepare_responses_request · function
vllm_mlx.server._prepare_responses_request(request: ResponsesRequest, *, validate_remote_media: bool = True) -> tuple[BaseEngine, ChatCompletionRequest, list[dict], dict]
Prepare a Responses request for execution on the chat engine.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
validate_remote_media |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
Returns
- Type:
tuple[BaseEngine, ChatCompletionRequest, list[dict], dict] - Direct return expressions:
(engine, chat_request, messages, chat_kwargs)
Exceptions and behavior
Function _prepare_responses_request calls _validate_model_name, get_engine, _responses_request_to_chat_request, logger.info; returns (engine, chat_request, messages, chat_kwargs).
No direct raise statement appears in this definition.
vllm_mlx.server._prepare_streaming_responses_request · function
vllm_mlx.server._prepare_streaming_responses_request(request: ResponsesRequest) -> tuple[BaseEngine, ChatCompletionRequest, list[dict], dict]
Prepare a streaming Responses request after eager URL validation.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[BaseEngine, ChatCompletionRequest, list[dict], dict] - Direct return expressions:
_prepare_responses_request(request, validate_remote_media=False)
Exceptions and behavior
Function _prepare_streaming_responses_request calls _prepare_responses_request; returns _prepare_responses_request(request, validate_remote_media=False).
No direct raise statement appears in this definition.
vllm_mlx.server._run_responses_request · function
async vllm_mlx.server._run_responses_request(request: ResponsesRequest, raw_request: Request) -> tuple[ResponseObject | None, list[dict]]
Execute a Responses API request against the backend chat engine.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
raw_request |
Request |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[ResponseObject | None, list[dict]] - Direct return expressions:
(None, []);(response_object, persisted_messages)
Exceptions and behavior
Function _run_responses_request calls _prepare_responses_request, _wait_with_disconnect, engine.chat, _parse_tool_calls_with_parser; awaits asynchronous work; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._stream_responses_request · function
Execute a Responses API request and stream SSE events incrementally.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
AsyncIterator[str] - Yields values incrementally.
Exceptions and behavior
Function _stream_responses_request calls _prepare_streaming_responses_request, chat_request.model_dump, _new_response_item_id, _build_response_object; yields values incrementally.
No direct raise statement appears in this definition.
vllm_mlx.server._stream_responses_request._start_text_item · nested function
Nested Function _stream_responses_request._start_text_item calls _new_response_item_id, events.append, _responses_sse_event, ResponseOutputItemAddedEvent; returns events.
Parameters
This callable has no explicit inputs.
Returns
- Type:
list[str] - Direct return expressions:
events
Exceptions and behavior
Nested Function _stream_responses_request._start_text_item calls _new_response_item_id, events.append, _responses_sse_event, ResponseOutputItemAddedEvent; returns events.
No direct raise statement appears in this definition.
vllm_mlx.server._stream_responses_request._start_reasoning_item · nested function
Nested Function _stream_responses_request._start_reasoning_item calls _new_response_item_id, events.append, _responses_sse_event, ResponseOutputItemAddedEvent; returns events.
Parameters
This callable has no explicit inputs.
Returns
- Type:
list[str] - Direct return expressions:
events
Exceptions and behavior
Nested Function _stream_responses_request._start_reasoning_item calls _new_response_item_id, events.append, _responses_sse_event, ResponseOutputItemAddedEvent; returns events.
No direct raise statement appears in this definition.
vllm_mlx.server._responses_sse_event · function
Encode a Responses API SSE event.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
event_type |
str |
yes |
none |
Required positional or keyword input. |
payload |
BaseModel \| dict |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
f'event: {event_type}\ndata: {data}\n\n'
Exceptions and behavior
Function _responses_sse_event calls isinstance, payload.model_dump_json, json.dumps; returns f'event: {event_type}\ndata: {data}\n\n'.
No direct raise statement appears in this definition.
vllm_mlx.server._strip_harmony_analysis_blocks · function
Remove harmony analysis-channel blocks (and their content) so reasoning text is never handed to the tool parser, while commentary/final text is preserved.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
text |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
_HARMONY_ANALYSIS_BLOCK_RE.sub('', text)
Exceptions and behavior
Function _strip_harmony_analysis_blocks calls _HARMONY_ANALYSIS_BLOCK_RE.sub; returns _HARMONY_ANALYSIS_BLOCK_RE.sub('', text).
No direct raise statement appears in this definition.
vllm_mlx.server._extract_reasoning_and_tool_calls · function
vllm_mlx.server._extract_reasoning_and_tool_calls(output_text: str, request: ChatCompletionRequest | None = None, *, allow_reasoning: bool = True, engine: BaseEngine | None = None) -> tuple[str | None, str | None, list[ToolCall] | None]
Extract reasoning first, then parse tool calls from the cleaned content.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
output_text |
str |
yes |
none |
Required positional or keyword input. |
request |
ChatCompletionRequest \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
allow_reasoning |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
engine |
BaseEngine \| None |
no |
None |
Optional keyword-only input; defaults to None. |
Returns
- Type:
tuple[str | None, str | None, list[ToolCall] | None] - Direct return expressions:
(reasoning_text, cleaned_text, tool_calls)
Exceptions and behavior
Function _extract_reasoning_and_tool_calls calls _reasoning_parser.extract_reasoning, getattr, _strip_harmony_analysis_blocks, _parse_tool_calls_with_parser; returns (reasoning_text, cleaned_text, tool_calls).
No direct raise statement appears in this definition.
vllm_mlx.server._detect_native_tool_support · function
Detect if the active tool parser supports native tool format.
Parameters
This callable has no explicit inputs.
Returns
- Type:
bool - Direct return expressions:
False;parser_cls.supports_native_format()
Exceptions and behavior
Function _detect_native_tool_support calls ToolParserManager.get_tool_parser, parser_cls.supports_native_format, logger.error, ToolParserManager.list_registered; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._detect_harmony_rendering · function
Detect whether the harmony rendering path should handle prompt building.
Parameters
This callable has no explicit inputs.
Returns
- Type:
bool - Direct return expressions:
False;True
Exceptions and behavior
Function _detect_harmony_rendering calls is_harmony_parser_name, logger.warning; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._tool_choice_disabled · function
Return True when tool_choice explicitly disables tool calling.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ChatCompletionRequest \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
False;tool_choice == 'none'
Exceptions and behavior
Function _tool_choice_disabled calls getattr, request.model_dump, request_dict.get; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._get_streaming_tool_parser · function
vllm_mlx.server._get_streaming_tool_parser(request: ChatCompletionRequest | None, engine: BaseEngine | None = None) -> not annotated
Get a streaming-capable tool parser for this request.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ChatCompletionRequest \| None |
yes |
none |
Required positional or keyword input. |
engine |
BaseEngine \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
not annotated - Direct return expressions:
None;_build_tool_parser(engine);parser
Exceptions and behavior
Function _get_streaming_tool_parser calls _tool_choice_disabled, _get_engine_tokenizer, _build_tool_parser, logger.warning; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._extract_streaming_tool_delta · function
vllm_mlx.server._extract_streaming_tool_delta(parser, previous_text: str, delta_text: str, request_context: dict) -> tuple[str, dict | None]
Parse one request-local streaming delta and return new accumulated text.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
parser |
not annotated |
yes |
none |
Required positional or keyword input. |
previous_text |
str |
yes |
none |
Required positional or keyword input. |
delta_text |
str |
yes |
none |
Required positional or keyword input. |
request_context |
dict |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[str, dict | None] - Direct return expressions:
(current_text, result)
Exceptions and behavior
Function _extract_streaming_tool_delta calls parser.extract_tool_calls_streaming; returns (current_text, result).
No direct raise statement appears in this definition.
vllm_mlx.server._stream_request_metadata · function
vllm_mlx.server._stream_request_metadata(request: ChatCompletionRequest) -> tuple[dict, list | None, bool]
Function _stream_request_metadata calls request.model_dump(include={'tools'}).get, request.model_dump, bool; returns ({'tools': tools or []}, tools, include_usage).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[dict, list | None, bool] - Direct return expressions:
({'tools': tools or []}, tools, include_usage)
Exceptions and behavior
Function _stream_request_metadata calls request.model_dump(include={'tools'}).get, request.model_dump, bool; returns ({'tools': tools or []}, tools, include_usage).
No direct raise statement appears in this definition.
vllm_mlx.server._parse_streaming_tool_content · function
vllm_mlx.server._parse_streaming_tool_content(parser, accumulated_text: str, delta_text: str, request_context: dict) -> tuple[str, dict | None, bool]
Function _parse_streaming_tool_content calls _extract_streaming_tool_delta; returns (accumulated_text, result, suppress).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
parser |
not annotated |
yes |
none |
Required positional or keyword input. |
accumulated_text |
str |
yes |
none |
Required positional or keyword input. |
delta_text |
str |
yes |
none |
Required positional or keyword input. |
request_context |
dict |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[str, dict | None, bool] - Direct return expressions:
(accumulated_text, result, suppress)
Exceptions and behavior
Function _parse_streaming_tool_content calls _extract_streaming_tool_delta; returns (accumulated_text, result, suppress).
No direct raise statement appears in this definition.
vllm_mlx.server._streaming_tool_markup_possible · function
Heuristic marker check to avoid parser work on ordinary text chunks.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
text |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
any((marker in text for marker in _STREAMING_TOOL_MARKERS)) or _STREAMING_BARE_BRACKET_MARKER.search(text) is not None …
Exceptions and behavior
Function _streaming_tool_markup_possible calls any, _STREAMING_BARE_BRACKET_MARKER.search, _STREAMING_BARE_BRACKET_PARTIAL.search; returns any((marker in text for marker in _STREAMING_TOOL_MARKERS)) or _STREAMING_BARE_BRACKET_MARKER.search(text) is not None ….
No direct raise statement appears in this definition.
vllm_mlx.server._streaming_tool_markup_possible_after_delta · function
vllm_mlx.server._streaming_tool_markup_possible_after_delta(accumulated_text: str, delta_text: str) -> bool
Check only the boundary window needed to detect newly appearing tool markup.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
accumulated_text |
str |
yes |
none |
Required positional or keyword input. |
delta_text |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
False;_streaming_tool_markup_possible(check_text)
Exceptions and behavior
Function _streaming_tool_markup_possible_after_delta calls _streaming_tool_markup_possible; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.load_embedding_model · function
vllm_mlx.server.load_embedding_model(model_name: str | None, *, lock: bool = False, reuse_existing: bool = True) -> None
Load or reuse the embedding model engine when configured.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model_name |
str \| None |
yes |
none |
Required positional or keyword input. |
lock |
bool |
no |
False |
Optional keyword-only input; defaults to False. |
reuse_existing |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Function load_embedding_model calls EmbeddingEngine, _embedding_engine.load; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server.load_reranker_model · function
vllm_mlx.server.load_reranker_model(model_name: str | None, *, lock: bool = False, reuse_existing: bool = True) -> None
Load or reuse the reranker model engine when configured.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model_name |
str \| None |
yes |
none |
Required positional or keyword input. |
lock |
bool |
no |
False |
Optional keyword-only input; defaults to False. |
reuse_existing |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Function load_reranker_model calls RerankEngine, _rerank_engine.load; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server.load_model · function
vllm_mlx.server.load_model(model_name: str, use_batching: bool = False, scheduler_config = None, stream_interval: int = 1, max_tokens: int = 32768, max_request_tokens: int = 32768, force_mllm: bool = False, gpu_memory_utilization: float = 0.9, served_model_name: str | None = None, trust_remote_code: bool = False, mtp: bool = False, prefill_step_size: int = 2048, specprefill_enabled: bool = False, specprefill_threshold: int = 8192, specprefill_keep_pct: float = 0.3, specprefill_backbone_pct: float = 0.0, specprefill_draft_model: str = None, mllm_draft_model: str | None = None, mllm_draft_kind: str | None = None, mllm_draft_block_size: int | None = None, warm_prompts_path: str | None = None, auto_unload_idle_seconds: float = 0.0, lazy_load_model: bool = False) -> not annotated
Load a model (auto-detects MLLM vs LLM).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model_name |
str |
yes |
none |
HuggingFace model name or local path |
use_batching |
bool |
no |
False |
Use continuous batching (BatchedEngine) vs simple mode (SimpleEngine) |
scheduler_config |
not annotated |
no |
None |
Scheduler config for batched mode |
stream_interval |
int |
no |
1 |
Tokens to batch before streaming (batched mode only) |
max_tokens |
int |
no |
32768 |
Default max tokens for generation |
max_request_tokens |
int |
no |
32768 |
Maximum max_tokens accepted from API clients |
force_mllm |
bool |
no |
False |
Force loading as MLLM even if not auto-detected |
gpu_memory_utilization |
float |
no |
0.9 |
Optional positional or keyword input; defaults to 0.9. |
served_model_name |
str \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
trust_remote_code |
bool |
no |
False |
Allow HuggingFace remote code execution during model/tokenizer loading |
mtp |
bool |
no |
False |
Enable native MTP speculative decoding (SimpleEngine only) |
prefill_step_size |
int |
no |
2048 |
Chunk size for prompt prefill processing (default: 2048) |
specprefill_enabled |
bool |
no |
False |
Enable SpecPrefill (SimpleEngine only) |
specprefill_threshold |
int |
no |
8192 |
Minimum suffix tokens to trigger SpecPrefill (default: 8192) |
specprefill_keep_pct |
float |
no |
0.3 |
Fraction of tokens to keep (default: 0.3) |
specprefill_backbone_pct |
float |
no |
0.0 |
Fraction of chunks reserved for evenly spaced coverage |
specprefill_draft_model |
str |
no |
None |
Path to small draft model for SpecPrefill scoring |
mllm_draft_model |
str \| None |
no |
None |
Optional MLLM speculative draft/assistant model path. |
mllm_draft_kind |
str \| None |
no |
None |
Optional mlx-vlm draft kind, for example "mtp". |
mllm_draft_block_size |
int \| None |
no |
None |
Optional speculative block size passed to mlx-vlm. |
warm_prompts_path |
str \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
auto_unload_idle_seconds |
float |
no |
0.0 |
Idle time before auto-unloading the main model. When non-zero, the main model is managed through lifecycle residency instead of being loaded immediately in this function. |
lazy_load_model |
bool |
no |
False |
When lifecycle residency is enabled, defer the first resident load until the first request instead of FastAPI lifespan startup. |
Returns
- Type:
not annotated - Direct return expressions:
None
Exceptions and behavior
Function load_model calls ValueError, RuntimeError, getattr, isinstance; can raise ValueError, RuntimeError; returns None.
Directly raised exceptions: ValueError, RuntimeError.
vllm_mlx.server.load_model_registry · function
Load a registry-backed model manager from YAML configuration.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
config_path |
str |
yes |
none |
Required positional or keyword input. |
defaults |
RegistryServeDefaults |
yes |
none |
Required keyword-only input. |
Returns
- Type:
None
Exceptions and behavior
Function load_model_registry calls load_registry_config, ModelManager, logger.info, len.
No direct raise statement appears in this definition.
vllm_mlx.server.get_usage · function
Extract usage metrics from GenerationOutput.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
output |
GenerationOutput |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
Usage - Direct return expressions:
Usage(prompt_tokens=total_prompt_tokens, completion_tokens=total_completion_tokens, total_tokens=total_prompt_tokens + …
Exceptions and behavior
Function get_usage calls hasattr, Usage; returns Usage(prompt_tokens=total_prompt_tokens, completion_tokens=total_completion_tokens, total_tokens=total_prompt_tokens + ….
No direct raise statement appears in this definition.
vllm_mlx.server.metrics · function
Prometheus scrape endpoint (disabled by default).
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
Response(content=payload, headers={'Content-Type': content_type})
Exceptions and behavior
Function metrics calls HTTPException, _metrics.render_metrics, Response; can raise HTTPException; returns Response(content=payload, headers={'Content-Type': content_type}).
Directly raised exceptions: HTTPException.
vllm_mlx.server.health · function
Health check endpoint.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
payload
Exceptions and behavior
Function health calls sum, _mcp_manager.get_server_status, len, _mcp_manager.get_all_tools; returns payload.
No direct raise statement appears in this definition.
vllm_mlx.server.status · function
Real-time status with per-request details for debugging and monitoring.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
{'status': 'running', 'model_manager': {'memory_budget_gb': round(_model_manager.memory_budget_bytes / 1024 ** 3, 2), '…;{'status': 'not_loaded', 'model': _model_name, 'residency': lifecycle, 'requests': []};{'status': 'running' if stats.get('running') else 'stopped', 'model': _model_name, 'residency': lifecycle, 'uptime_s': …
Exceptions and behavior
Function status calls round, _model_manager.list_models, _public_lifecycle_status, _get_lifecycle_status; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.cache_stats · function
Get cache statistics for debugging and monitoring.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
{'engine_cache': engine_cache, 'multimodal_kv_cache': get_multimodal_kv_cache_stats(), 'pixel_values_cache': get_pixel_…;{'engine_cache': engine_cache, 'error': 'Cache stats not available (mlx_vlm not loaded)'}
Exceptions and behavior
Function cache_stats calls hasattr, _engine.get_cache_stats, get_multimodal_kv_cache_stats, get_pixel_values_cache_stats; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.clear_cache · function
Clear all caches.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
{'status': 'cleared', 'engine_cache': cleared_engine, 'caches': ['multimodal_kv', 'pixel_values', 'pil_image']};{'status': 'cleared', 'engine_cache': cleared_engine, 'error': 'Cache clear not available (mlx_vlm not loaded)'}
Exceptions and behavior
Function clear_cache calls hasattr, _engine.clear_runtime_caches, logger.warning, str; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.clear_prefix_cache · function
Clear the text prefix cache used for KV reuse in continuous batching.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
{'status': 'no_engine'};{'status': status, 'rewarm_scheduled': rewarm_scheduled}
Exceptions and behavior
Function clear_prefix_cache calls hasattr, _engine.clear_prefix_cache, logger.warning, _sanitize_log_text; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.clear_prefix_cache._rewarm · nested function
Nested Function clear_prefix_cache._rewarm calls load_warmup_file, warm_prefix_cache, logger.info, logger.warning; awaits asynchronous work.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated
Exceptions and behavior
Nested Function clear_prefix_cache._rewarm calls load_warmup_file, warm_prefix_cache, logger.info, logger.warning; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server.cancel_request · function
Cancel an active or queued request.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_id |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
{'object': 'request.cancel', 'id': request_id, 'cancelled': True, 'model': _model_name}
Exceptions and behavior
Function cancel_request calls get_engine, engine.abort_request, logger.exception, HTTPException; awaits asynchronous work; can raise HTTPException; returns {'object': 'request.cancel', 'id': request_id, 'cancelled': True, 'model': _model_name}.
Directly raised exceptions: HTTPException.
vllm_mlx.server.delete_request · function
OpenAI-style alias for cancelling an active or queued request.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_id |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
await cancel_request(request_id)
Exceptions and behavior
Function delete_request calls cancel_request; awaits asynchronous work; returns await cancel_request(request_id).
No direct raise statement appears in this definition.
vllm_mlx.server.list_models · function
List available models.
Parameters
This callable has no explicit inputs.
Returns
- Type:
ModelsResponse - Direct return expressions:
ModelsResponse(data=models)
Exceptions and behavior
Function list_models calls models.extend, ModelInfo, _model_manager.list_models, models.append; returns ModelsResponse(data=models).
No direct raise statement appears in this definition.
vllm_mlx.server.create_embeddings · function
Create embeddings for the given input text(s).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
EmbeddingRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
EmbeddingResponse - Direct return expressions:
response
Exceptions and behavior
Function create_embeddings calls _metrics.track_inference, resolve_embedding_model_name, load_embedding_model, isinstance; can raise HTTPException; returns response.
Directly raised exceptions: HTTPException.
vllm_mlx.server.rerank_documents · function
Rerank documents against a query using a cross-encoder model.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
RerankRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
RerankResponse - Direct return expressions:
RerankResponse(model=model_name, results=results, usage=RerankUsage(total_tokens=total_tokens))
Exceptions and behavior
Function rerank_documents calls HTTPException, request.query.strip, len, isinstance; awaits asynchronous work; can raise HTTPException; returns RerankResponse(model=model_name, results=results, usage=RerankUsage(total_tokens=total_tokens)).
Directly raised exceptions: HTTPException.
vllm_mlx.server.list_mcp_tools · function
List all available MCP tools.
Parameters
This callable has no explicit inputs.
Returns
- Type:
MCPToolsResponse - Direct return expressions:
MCPToolsResponse(tools=[], count=0);MCPToolsResponse(tools=tools, count=len(tools))
Exceptions and behavior
Function list_mcp_tools calls MCPToolsResponse, _mcp_manager.get_all_tools, tools.append, MCPToolInfo; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.list_mcp_servers · function
Get status of all MCP servers.
Parameters
This callable has no explicit inputs.
Returns
- Type:
MCPServersResponse - Direct return expressions:
MCPServersResponse(servers=[]);MCPServersResponse(servers=servers)
Exceptions and behavior
Function list_mcp_servers calls MCPServersResponse, _mcp_manager.get_server_status, servers.append, MCPServerInfo; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.execute_mcp_tool · function
Execute an MCP tool.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
MCPExecuteRequest |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
MCPExecuteResponse - Direct return expressions:
MCPExecuteResponse(tool_name=result.tool_name, content=result.content, is_error=result.is_error, error_message=result.e…
Exceptions and behavior
Function execute_mcp_tool calls HTTPException, ToolExecutor, uuid.uuid4, _mcp_executor.execute_tool_calls; awaits asynchronous work; can raise HTTPException; returns MCPExecuteResponse(tool_name=result.tool_name, content=result.content, is_error=result.is_error, error_message=result.e….
Directly raised exceptions: HTTPException.
vllm_mlx.server.create_transcription · function
async vllm_mlx.server.create_transcription(file: UploadFile, model: str = 'whisper-large-v3', language: str | None = None, response_format: str = 'json') -> not annotated
Transcribe audio to text (OpenAI Whisper API compatible).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
file |
UploadFile |
yes |
none |
Required positional or keyword input. |
model |
str |
no |
'whisper-large-v3' |
Optional positional or keyword input; defaults to 'whisper-large-v3'. |
language |
str \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
response_format |
str |
no |
'json' |
Optional positional or keyword input; defaults to 'json'. |
Returns
- Type:
not annotated - Direct return expressions:
result.text;{'text': result.text, 'language': result.language, 'duration': result.duration}
Exceptions and behavior
Function create_transcription calls _metrics.track_inference, resolve_stt_model_name, STTEngine, _stt_engine.load; awaits asynchronous work; can raise HTTPException; has 2 explicit return paths.
Directly raised exceptions: HTTPException.
vllm_mlx.server.create_speech · function
async vllm_mlx.server.create_speech(model: str = 'kokoro', input: str = '', voice: str = 'af_heart', speed: float = 1.0, response_format: str = 'wav') -> not annotated
Generate speech from text (OpenAI TTS API compatible).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model |
str |
no |
'kokoro' |
Optional positional or keyword input; defaults to 'kokoro'. |
input |
str |
no |
'' |
Optional positional or keyword input; defaults to ''. |
voice |
str |
no |
'af_heart' |
Optional positional or keyword input; defaults to 'af_heart'. |
speed |
float |
no |
1.0 |
Optional positional or keyword input; defaults to 1.0. |
response_format |
str |
no |
'wav' |
Optional positional or keyword input; defaults to 'wav'. |
Returns
- Type:
not annotated - Direct return expressions:
Response(content=audio_bytes, media_type=content_type)
Exceptions and behavior
Function create_speech calls _metrics.track_inference, resolve_tts_model_name, validate_tts_input_length, TTSEngine; can raise HTTPException; returns Response(content=audio_bytes, media_type=content_type).
Directly raised exceptions: HTTPException.
vllm_mlx.server.list_voices · function
List available voices for a TTS model.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model |
str |
no |
'kokoro' |
Optional positional or keyword input; defaults to 'kokoro'. |
Returns
- Type:
not annotated - Direct return expressions:
{'voices': KOKORO_VOICES};{'voices': CHATTERBOX_VOICES};{'voices': ['default']}
Exceptions and behavior
Function list_voices calls model.lower; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._ensure_sse_terminal · function
async vllm_mlx.server._ensure_sse_terminal(generator: AsyncIterator[str], terminal_frame: str) -> AsyncIterator[str]
Guarantee that terminal_frame is emitted exactly once at the end of generator, even if the generator raises mid-stream.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
generator |
AsyncIterator[str] |
yes |
none |
Required positional or keyword input. |
terminal_frame |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
AsyncIterator[str] - Yields values incrementally.
Exceptions and behavior
Function _ensure_sse_terminal calls logger.error; yields values incrementally.
No direct raise statement appears in this definition.
vllm_mlx.server._find_uvicorn_cycle · function
Walk through middleware wrappers to find uvicorn's RequestResponseCycle.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
obj |
not annotated |
yes |
none |
Required positional or keyword input. |
depth |
not annotated |
no |
0 |
Optional positional or keyword input; defaults to 0. |
visited |
not annotated |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
not annotated - Direct return expressions:
None;obj;result
Exceptions and behavior
Function _find_uvicorn_cycle calls set, id, visited.add, hasattr; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._is_client_disconnected · function
Reliable client disconnect check.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
raw_request |
Request |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
True;False
Exceptions and behavior
Function _is_client_disconnected calls getattr, _find_uvicorn_cycle; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._disconnect_guard · function
async vllm_mlx.server._disconnect_guard(generator: AsyncIterator[str], raw_request: Request, poll_interval: float = 0.5, heartbeat_interval: float = 5.0, cleanup = None, timeout: float | None = None) -> AsyncIterator[str]
Wrap streaming generator to abort on client disconnect.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
generator |
AsyncIterator[str] |
yes |
none |
Required positional or keyword input. |
raw_request |
Request |
yes |
none |
Required positional or keyword input. |
poll_interval |
float |
no |
0.5 |
Optional positional or keyword input; defaults to 0.5. |
heartbeat_interval |
float |
no |
5.0 |
Optional positional or keyword input; defaults to 5.0. |
cleanup |
not annotated |
no |
None |
Optional positional or keyword input; defaults to None. |
timeout |
float \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
AsyncIterator[str] - Yields values incrementally.
Exceptions and behavior
Function _disconnect_guard calls _time.monotonic, logger.info, generator.__aiter__, asyncio.create_task; awaits asynchronous work; yields values incrementally.
No direct raise statement appears in this definition.
vllm_mlx.server._disconnect_guard._elapsed · nested function
Nested Function _disconnect_guard._elapsed calls _time.monotonic; returns f'{_time.monotonic() - _t0:.1f}s'.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
f'{_time.monotonic() - _t0:.1f}s'
Exceptions and behavior
Nested Function _disconnect_guard._elapsed calls _time.monotonic; returns f'{_time.monotonic() - _t0:.1f}s'.
No direct raise statement appears in this definition.
vllm_mlx.server._disconnect_guard._wait_disconnect · nested function
Nested Function _disconnect_guard._wait_disconnect calls asyncio.sleep, _is_client_disconnected, logger.info, _elapsed; awaits asynchronous work; returns None.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
None
Exceptions and behavior
Nested Function _disconnect_guard._wait_disconnect calls asyncio.sleep, _is_client_disconnected, logger.info, _elapsed; awaits asynchronous work; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server._disconnect_guard._deferred_generator_close · nested function
Nested Function _disconnect_guard._deferred_generator_close calls asyncio.sleep, _gen_to_close.aclose, logger.debug, type; awaits asynchronous work.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated
Exceptions and behavior
Nested Function _disconnect_guard._deferred_generator_close calls asyncio.sleep, _gen_to_close.aclose, logger.debug, type; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server._wait_with_disconnect · function
async vllm_mlx.server._wait_with_disconnect(coro, raw_request: Request, timeout: float, poll_interval: float = 0.5, timeout_detail_seconds: float | None = None, cleanup_result = None) -> not annotated
Run a coroutine with both timeout and client disconnect detection.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
coro |
not annotated |
yes |
none |
Required positional or keyword input. |
raw_request |
Request |
yes |
none |
Required positional or keyword input. |
timeout |
float |
yes |
none |
Required positional or keyword input. |
poll_interval |
float |
no |
0.5 |
Optional positional or keyword input; defaults to 0.5. |
timeout_detail_seconds |
float \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
cleanup_result |
not annotated |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
not annotated - Direct return expressions:
None;task.result()
Exceptions and behavior
Function _wait_with_disconnect calls _time.monotonic, asyncio.ensure_future, asyncio.create_task, _wait_disconnect; awaits asynchronous work; can raise HTTPException; has 2 explicit return paths.
Directly raised exceptions: HTTPException.
vllm_mlx.server._wait_with_disconnect._wait_disconnect · nested function
Nested Function _wait_with_disconnect._wait_disconnect calls asyncio.sleep, _is_client_disconnected, logger.info, _time.monotonic; awaits asynchronous work; returns None.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
None
Exceptions and behavior
Nested Function _wait_with_disconnect._wait_disconnect calls asyncio.sleep, _is_client_disconnected, logger.info, _time.monotonic; awaits asynchronous work; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server._start_request_budget · function
Return the total timeout and absolute deadline for a request.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
timeout |
float \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[float, float] - Direct return expressions:
(total_timeout, time.monotonic() + total_timeout)
Exceptions and behavior
Function _start_request_budget calls time.monotonic; returns (total_timeout, time.monotonic() + total_timeout).
No direct raise statement appears in this definition.
vllm_mlx.server._remaining_request_timeout · function
Compute remaining request budget or raise the standard timeout error.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
total_timeout |
float |
yes |
none |
Required positional or keyword input. |
deadline |
float |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
float - Direct return expressions:
remaining
Exceptions and behavior
Function _remaining_request_timeout calls time.monotonic, HTTPException; can raise HTTPException; returns remaining.
Directly raised exceptions: HTTPException.
vllm_mlx.server._acquire_default_engine_for_request · function
async vllm_mlx.server._acquire_default_engine_for_request(raw_request: Request, *, total_timeout: float, deadline: float, count_activity: bool = True, model: str | None = None) -> BaseEngine | None
Acquire the engine for a request, using the model registry when active.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
raw_request |
Request |
yes |
none |
Required positional or keyword input. |
total_timeout |
float |
yes |
none |
Required keyword-only input. |
deadline |
float |
yes |
none |
Required keyword-only input. |
count_activity |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
model |
str \| None |
no |
None |
Optional keyword-only input; defaults to None. |
Returns
- Type:
BaseEngine | None - Direct return expressions:
await _registry_acquire();await _wait_with_disconnect(_registry_acquire(), raw_request, timeout=_remaining_request_timeout(total_timeout, deadlin…;await acquire_coro;await _wait_with_disconnect(acquire_coro, raw_request, timeout=_remaining_request_timeout(total_timeout, deadline), tim…
Exceptions and behavior
Function _acquire_default_engine_for_request calls _registry_acquire, _wait_with_disconnect, _remaining_request_timeout, _acquire_default_engine; awaits asynchronous work; has 4 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._acquire_default_engine_for_request._registry_acquire · nested function
Nested Function _acquire_default_engine_for_request._registry_acquire calls _acquire_request_model, id; awaits asynchronous work; returns ctx.engine.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated - Direct return expressions:
ctx.engine
Exceptions and behavior
Nested Function _acquire_default_engine_for_request._registry_acquire calls _acquire_request_model, id; awaits asynchronous work; returns ctx.engine.
No direct raise statement appears in this definition.
vllm_mlx.server._acquire_default_engine_for_request._registry_cleanup · nested function
async vllm_mlx.server._acquire_default_engine_for_request._registry_cleanup(_result) -> not annotated
Nested Function _acquire_default_engine_for_request._registry_cleanup calls _active_request_contexts.pop, id, ctx.release; awaits asynchronous work.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
_result |
not annotated |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated
Exceptions and behavior
Nested Function _acquire_default_engine_for_request._registry_cleanup calls _active_request_contexts.pop, id, ctx.release; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server._release_engine_for_request · function
async vllm_mlx.server._release_engine_for_request(raw_request: Request | None, *, count_activity: bool = True) -> None
Release the engine acquired for this request.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
raw_request |
Request \| None |
yes |
none |
Required positional or keyword input. |
count_activity |
bool |
no |
True |
Optional keyword-only input; defaults to True. |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Function _release_engine_for_request calls _active_request_contexts.pop, id, ctx.release, _release_default_engine; awaits asynchronous work; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server._make_release_cleanup · function
Return a cleanup callable suitable for _disconnect_guard.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
raw_request |
Request \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
_cleanup;_release_default_engine
Exceptions and behavior
Function _make_release_cleanup has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._make_release_cleanup._cleanup · nested function
Nested Function _make_release_cleanup._cleanup calls _active_request_contexts.pop, id, ctx.release, _release_default_engine; awaits asynchronous work.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated
Exceptions and behavior
Nested Function _make_release_cleanup._cleanup calls _active_request_contexts.pop, id, ctx.release, _release_default_engine; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server.create_completion · function
async vllm_mlx.server.create_completion(request: CompletionRequest, raw_request: Request) -> not annotated
Create a text completion.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
CompletionRequest |
yes |
none |
Required positional or keyword input. |
raw_request |
Request |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
Response(status_code=499);response;CompletionResponse(model=_response_model_name(request.model), choices=choices, usage=Usage(prompt_tokens=total_prompt_t…
Exceptions and behavior
Function create_completion calls _validate_model_name, _resolve_request_max_tokens, _metrics.track_inference, isinstance; awaits asynchronous work; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.create_chat_completion · function
async vllm_mlx.server.create_chat_completion(request: ChatCompletionRequest, raw_request: Request) -> not annotated
Create a chat completion (supports multimodal content for VLM models).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
raw_request |
Request |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
Response(status_code=499);response;ChatCompletionResponse(model=_response_model_name(request.model), choices=[ChatCompletionChoice(message=AssistantMessag…
Exceptions and behavior
Function create_chat_completion calls _validate_model_name, _resolve_request_max_tokens, _metrics.track_inference, _start_request_budget; awaits asynchronous work; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._normalize_messages · function
Normalize message roles and merge consecutive same-role messages.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
messages |
list[dict] |
yes |
none |
List of message dicts with 'role' and 'content' keys. |
Returns
- Type:
list[dict] - Direct return expressions:
messages;merged
Exceptions and behavior
Function _normalize_messages calls messages[0].copy, _ROLE_MAP.get, isinstance, prev.get; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._get_engine_tokenizer · function
Return the tokenizer backing engine, if exposed.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
not annotated |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
object | None - Direct return expressions:
tok;None
Exceptions and behavior
Function _get_engine_tokenizer calls getattr; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.create_response · function
async vllm_mlx.server.create_response(request: ResponsesRequest, raw_request: Request) -> not annotated
Create a Responses API response.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
ResponsesRequest |
yes |
none |
Required positional or keyword input. |
raw_request |
Request |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
StreamingResponse(_disconnect_guard(_stream_responses_request(request), raw_request), media_type='text/event-stream');Response(status_code=499);response_object
Exceptions and behavior
Function create_response calls _responses_request_to_chat_request, _validate_remote_media_urls, StreamingResponse, _disconnect_guard; awaits asynchronous work; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._get_forced_tool_name · function
Extract forced tool name from tool_choice, if any.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tool_choice |
not annotated |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str | None - Direct return expressions:
None;func.get('name')
Exceptions and behavior
Function _get_forced_tool_name calls isinstance, tool_choice.get, func.get; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._apply_forced_tool_choice · function
vllm_mlx.server._apply_forced_tool_choice(tool_choice, tools, messages, chat_kwargs = None) -> not annotated
Apply forced tool_choice by filtering tools and injecting instructions.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tool_choice |
not annotated |
yes |
none |
The tool_choice value from the request |
tools |
not annotated |
yes |
none |
List of converted tools for the template |
messages |
not annotated |
yes |
none |
The message list (will be copied if modified) |
chat_kwargs |
not annotated |
no |
None |
Optional dict to modify (e.g. disable thinking) |
Returns
- Type:
not annotated - Direct return expressions:
(tools, messages)
Exceptions and behavior
Function _apply_forced_tool_choice calls _get_forced_tool_name, _tool_name, ValueError, _inject_json_instruction; can raise ValueError; returns (tools, messages).
Directly raised exceptions: ValueError.
vllm_mlx.server._tool_name · function
Extract function name from a tool definition dict.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tool |
dict |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str | None - Direct return expressions:
func.get('name');None
Exceptions and behavior
Function _tool_name calls tool.get, isinstance, func.get; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._inject_json_instruction · function
Inject JSON instruction into messages.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
messages |
list |
yes |
none |
Required positional or keyword input. |
instruction |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list - Direct return expressions:
messages
Exceptions and behavior
Function _inject_json_instruction calls list, enumerate, isinstance, msg.get; returns messages.
No direct raise statement appears in this definition.
vllm_mlx.server._convert_anthropic_stop_reason · function
Convert OpenAI finish_reason to Anthropic stop_reason.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
openai_reason |
str \| None |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
mapping.get(openai_reason or '', 'end_turn')
Exceptions and behavior
Function _convert_anthropic_stop_reason calls mapping.get; returns mapping.get(openai_reason or '', 'end_turn').
No direct raise statement appears in this definition.
vllm_mlx.server._prepare_anthropic_endpoint_invocation · function
vllm_mlx.server._prepare_anthropic_endpoint_invocation(engine: BaseEngine, openai_request: ChatCompletionRequest, effective_max_tokens: int) -> PreparedChatInvocation
Prepare Anthropic invocation and convert URL-safety errors to 400s.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
openai_request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
effective_max_tokens |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
PreparedChatInvocation - Direct return expressions:
_prepare_anthropic_invocation(engine, openai_request, effective_max_tokens)
Exceptions and behavior
Function _prepare_anthropic_endpoint_invocation calls _prepare_anthropic_invocation, _raise_remote_media_http_error; returns _prepare_anthropic_invocation(engine, openai_request, effective_max_tokens).
No direct raise statement appears in this definition.
vllm_mlx.server.create_anthropic_message · function
Anthropic Messages API endpoint.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
Request |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
Response(status_code=499);response;Response(content=anthropic_response.model_dump_json(exclude_none=True), media_type='application/json')
Exceptions and behavior
Function create_anthropic_message calls _metrics.track_inference, request.json, str, request.body; awaits asynchronous work; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server.count_anthropic_tokens · function
Count tokens for an Anthropic Messages API request.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request |
Request |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
Response(status_code=499);{'input_tokens': total_tokens}
Exceptions and behavior
Function count_anthropic_tokens calls request.json, body.get, isinstance, _validate_model_name; awaits asynchronous work; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.server._emit_content_pieces · function
vllm_mlx.server._emit_content_pieces(pieces: list[tuple[str, str]], current_block_type: str | None, block_index: int) -> tuple[list[str], str | None, int]
Emit Anthropic SSE events for content pieces from the think router.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
pieces |
list[tuple[str, str]] |
yes |
none |
List of (block_type, text) from StreamingThinkRouter |
current_block_type |
str \| None |
yes |
none |
Current open block type, or None |
block_index |
int |
yes |
none |
Current block index |
Returns
- Type:
tuple[list[str], str | None, int] - Direct return expressions:
(events, current_block_type, block_index)
Exceptions and behavior
Function _emit_content_pieces calls events.append, json.dumps; returns (events, current_block_type, block_index).
No direct raise statement appears in this definition.
vllm_mlx.server._stream_anthropic_messages · function
async vllm_mlx.server._stream_anthropic_messages(engine: BaseEngine, openai_request: ChatCompletionRequest, anthropic_request: AnthropicRequest, prepared: PreparedChatInvocation, metrics_tracker = None) -> AsyncIterator[str]
Stream Anthropic Messages API SSE events.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
openai_request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
anthropic_request |
AnthropicRequest |
yes |
none |
Required positional or keyword input. |
prepared |
PreparedChatInvocation |
yes |
none |
Required positional or keyword input. |
metrics_tracker |
not annotated |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
AsyncIterator[str] - Yields values incrementally.
Exceptions and behavior
Function _stream_anthropic_messages calls uuid.uuid4, time.perf_counter, dict, _response_model_name; yields values incrementally.
No direct raise statement appears in this definition.
vllm_mlx.server.stream_completion · function
async vllm_mlx.server.stream_completion(engine: BaseEngine, prompt: str, request: CompletionRequest, max_tokens: int, repetition_penalty: float | None = None, metrics_tracker = None) -> AsyncIterator[str]
Stream completion response.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
prompt |
str |
yes |
none |
Required positional or keyword input. |
request |
CompletionRequest |
yes |
none |
Required positional or keyword input. |
max_tokens |
int |
yes |
none |
Required positional or keyword input. |
repetition_penalty |
float \| None |
no |
None |
Optional positional or keyword input; defaults to None. |
metrics_tracker |
not annotated |
no |
None |
Optional positional or keyword input; defaults to None. |
Returns
- Type:
AsyncIterator[str] - Yields values incrementally.
Exceptions and behavior
Function stream_completion calls _resolve_temperature, _resolve_top_p, _resolve_top_k, _resolve_min_p; yields values incrementally.
No direct raise statement appears in this definition.
vllm_mlx.server.stream_chat_completion · function
async vllm_mlx.server.stream_chat_completion(engine: BaseEngine, messages: list, request: ChatCompletionRequest, metrics_tracker = None, **kwargs) -> AsyncIterator[str]
Stream chat completion response.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
BaseEngine |
yes |
none |
Required positional or keyword input. |
messages |
list |
yes |
none |
Required positional or keyword input. |
request |
ChatCompletionRequest |
yes |
none |
Required positional or keyword input. |
metrics_tracker |
not annotated |
no |
None |
Optional positional or keyword input; defaults to None. |
**kwargs |
not annotated |
no |
none |
Additional variadic keyword inputs accepted by this callable. |
Returns
- Type:
AsyncIterator[str] - Yields values incrementally.
Exceptions and behavior
Function stream_chat_completion calls uuid.uuid4, time.perf_counter, _stream_request_metadata, ChatCompletionChunk; yields values incrementally.
No direct raise statement appears in this definition.
vllm_mlx.server.init_mcp · function
Initialize MCP manager from config file.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
config_path |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated
Exceptions and behavior
Function init_mcp calls load_mcp_config, MCPClientManager, _mcp_manager.start, ToolSandbox; awaits asynchronous work.
No direct raise statement appears in this definition.
vllm_mlx.server._make_keepalive_http_protocol · function
Create a uvicorn HTTP protocol class with aggressive TCP keepalive.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
idle |
not annotated |
no |
10 |
Optional positional or keyword input; defaults to 10. |
interval |
not annotated |
no |
5 |
Optional positional or keyword input; defaults to 5. |
count |
not annotated |
no |
3 |
Optional positional or keyword input; defaults to 3. |
Returns
- Type:
not annotated - Direct return expressions:
_KeepaliveProtocol
Exceptions and behavior
Function _make_keepalive_http_protocol returns _KeepaliveProtocol.
No direct raise statement appears in this definition.
vllm_mlx.server._make_keepalive_http_protocol._KeepaliveProtocol · nested class
Nested Class _make_keepalive_http_protocol._KeepaliveProtocol derives from _Base and declares 1 direct member(s).
Parameters
This callable has no explicit inputs.
Returns
- Constructs:
vllm_mlx.server._make_keepalive_http_protocol._KeepaliveProtocol
Exceptions and behavior
Nested Class _make_keepalive_http_protocol._KeepaliveProtocol derives from _Base and declares 1 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.server._make_keepalive_http_protocol._KeepaliveProtocol.connection_made · nested function
vllm_mlx.server._make_keepalive_http_protocol._KeepaliveProtocol.connection_made(transport) -> not annotated
Nested Function _make_keepalive_http_protocol._KeepaliveProtocol.connection_made calls super().connection_made, super, transport.get_extra_info, sock.setsockopt; returns None.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
transport |
not annotated |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated - Direct return expressions:
None
Exceptions and behavior
Nested Function _make_keepalive_http_protocol._KeepaliveProtocol.connection_made calls super().connection_made, super, transport.get_extra_info, sock.setsockopt; returns None.
No direct raise statement appears in this definition.
vllm_mlx.server.main · function
Run the server.
Parameters
This callable has no explicit inputs.
Returns
- Type:
not annotated
Exceptions and behavior
Function main calls create_parser, parser.parse_args, _metrics.configure, RateLimiter.
No direct raise statement appears in this definition.
vllm_mlx.server.create_parser · function
Create the standalone server CLI parser.
Parameters
This callable has no explicit inputs.
Returns
- Type:
argparse.ArgumentParser - Direct return expressions:
parser
Exceptions and behavior
Function create_parser calls argparse.ArgumentParser, parser.add_argument, make_positive_int_arg_parser, list_parsers; returns parser.
No direct raise statement appears in this definition.
Complete symbol map¶
This map also includes private definitions and nested helpers. The signature column exposes every explicit input even when an internal helper has no dedicated parameter prose.
| Symbol | Kind | Signature and inputs | What it does | Source |
|---|---|---|---|---|
_resolve_temperature |
function | _resolve_temperature(request_value: float \| None) -> float |
Resolve temperature: request > CLI default > fallback. | #L225-L231 |
_resolve_top_p |
function | _resolve_top_p(request_value: float \| None) -> float |
Resolve top_p: request > CLI default > fallback. | #L234-L240 |
_resolve_top_k |
function | _resolve_top_k(request_value: int \| None) -> int |
Resolve top_k: request > CLI default > fallback. | #L243-L249 |
_resolve_min_p |
function | _resolve_min_p(request_value: float \| None) -> float |
Resolve min_p: request > CLI default > fallback. | #L252-L258 |
_resolve_presence_penalty |
function | _resolve_presence_penalty(request_value: float \| None) -> float |
Resolve presence_penalty: request > CLI default > fallback. | #L261-L267 |
_resolve_repetition_penalty |
function | _resolve_repetition_penalty(request_value: float \| None) -> float |
Resolve repetition_penalty: request > CLI default > fallback. | #L270-L276 |
_resolve_request_max_tokens |
function | _resolve_request_max_tokens(requested_value: int \| None) -> int |
Resolve and validate a request's max_tokens budget. | #L279-L288 |
_resolve_chat_template_kwargs |
function | _resolve_chat_template_kwargs(request_value: dict[str, object] \| None) -> dict[str, object] |
Resolve chat template kwargs: request > server default > empty dict. | #L291-L300 |
PreparedChatInvocation |
class | PreparedChatInvocation(messages: list[dict], chat_kwargs: dict[str, object], response_format: object \| None, json_logits_processor: object \| None, thinking_processor: object \| None = None) |
Fully prepared inputs for a single engine.chat/stream_chat call. | #L304-L311 |
_prepare_chat_messages |
function | _prepare_chat_messages(engine: BaseEngine, request_messages: list[Message \| dict]) -> tuple[list[dict], list, list, list, bool] |
Normalize messages and collect media once for both stream/non-stream paths. | #L314-L398 |
_iter_remote_media_urls |
function | _iter_remote_media_urls(messages: list[Message \| dict]) -> not annotated |
Yield remote media URLs from OpenAI-style multimodal message content. | #L401-L429 |
_validate_remote_media_urls |
function | _validate_remote_media_urls(messages: list[Message \| dict]) -> None |
Validate remote media URLs during request preparation. | #L432-L435 |
_raise_remote_media_http_error |
function | _raise_remote_media_http_error(exc: UnsafeRemoteURLError) -> None |
Log internal URL-safety detail while returning a generic client error. | #L438-L444 |
_prepare_json_logits_processor |
function | _prepare_json_logits_processor(engine: BaseEngine, messages: list[dict], response_format: object \| None, *, tools: list \| None, tool_choice: object \| None, log_context: str \| None = None, thinking_model: bool = False) -> tuple[list[dict], object \| None] |
Inject response_format instruction and build constrained decoding processor. | #L447-L497 |
_build_thinking_processor |
function | _build_thinking_processor(engine: BaseEngine, thinking_token_budget: int, *, inner: object \| None = None, prompt_has_think_tag: bool = True) -> object \| None |
Build a ThinkingAwareLogitsProcessor if the tokenizer has think tokens. | #L500-L554 |
_resolve_no_final_content_token_limit |
function | _resolve_no_final_content_token_limit() -> int \| None |
Function _resolve_no_final_content_token_limit calls os.environ.get, raw.strip, int, logger.warning; has 2 explicit return paths. |
#L557-L568 |
_generation_metadata |
function | _generation_metadata(thinking_processor: object \| None) -> GenerationMetadata \| None |
Function _generation_metadata calls GenerationMetadata, getattr, bool; has 2 explicit return paths. |
#L571-L583 |
_ThinkingAwareLogitsProcessor |
class | _ThinkingAwareLogitsProcessor(inner, prompt_has_think_tag: bool = False) |
Wrap a JSONSchemaLogitsProcessor so JSON constraining only activates after the model emits </think>, letting it reason freely first. |
#L586-L697 |
_ThinkingAwareLogitsProcessor.__init__ |
method | _ThinkingAwareLogitsProcessor.__init__(inner, prompt_has_think_tag: bool = False) -> not annotated |
Method _ThinkingAwareLogitsProcessor.__init__ updates self._inner, self._active, self._in_thinking, self._waiting_for_json. |
#L597-L608 |
_ThinkingAwareLogitsProcessor._scan_for_json_start |
method | _ThinkingAwareLogitsProcessor._scan_for_json_start(tokens_list, tokens, logits) -> not annotated |
Scan generated tokens for the first { or [. |
#L610-L635 |
_ThinkingAwareLogitsProcessor.__call__ |
method | _ThinkingAwareLogitsProcessor.__call__(tokens, logits) -> not annotated |
Method _ThinkingAwareLogitsProcessor.__call__ updates self._base_prompt_len, self._in_thinking, self._waiting_for_json, self._json_scan_offset; calls self._inner, hasattr, tokens.tolist, list; has 3 explicit return paths. |
#L637-L688 |
_ThinkingAwareLogitsProcessor.schema |
method | _ThinkingAwareLogitsProcessor.schema() -> not annotated |
Method _ThinkingAwareLogitsProcessor.schema returns self._inner.schema. |
#L692-L693 |
_ThinkingAwareLogitsProcessor._disabled |
method | _ThinkingAwareLogitsProcessor._disabled() -> not annotated |
Method _ThinkingAwareLogitsProcessor._disabled returns self._inner._disabled. |
#L696-L697 |
_attach_response_format_logits_processor |
function | _attach_response_format_logits_processor(chat_kwargs: dict, json_logits_processor: object) -> object |
Attach response_format constraints and keep thinking disabled. | #L700-L717 |
_coerce_logit_bias |
function | _coerce_logit_bias(logit_bias: dict[str, float]) -> dict[int, float] |
Function _coerce_logit_bias calls logit_bias.items, int, float, HTTPException; can raise HTTPException; returns coerced. |
#L720-L730 |
_attach_logit_bias_processor |
function | _attach_logit_bias_processor(chat_kwargs: dict, logit_bias: dict[str, float] \| None) -> not annotated |
Function _attach_logit_bias_processor calls make_logits_processors, _coerce_logit_bias, chat_kwargs.get, list; returns None. |
#L733-L744 |
_prepare_chat_completion_invocation |
function | _prepare_chat_completion_invocation(engine: BaseEngine, request: ChatCompletionRequest, effective_max_tokens: int) -> PreparedChatInvocation |
Precompute messages, kwargs, and decoding constraints for chat completions. | #L747-L855 |
_prepare_anthropic_invocation |
function | _prepare_anthropic_invocation(engine: BaseEngine, openai_request: ChatCompletionRequest, effective_max_tokens: int) -> PreparedChatInvocation |
Precompute messages, kwargs, and decoding constraints for Anthropic API. | #L858-L910 |
_thinking_disabled |
function | _thinking_disabled(request, chat_kwargs: dict \| None = None) -> bool |
Return True iff thinking is explicitly disabled for this request. | #L934-L950 |
_strip_backslash_before_unicode |
function | _strip_backslash_before_unicode(obj: object) -> object |
Remove spurious backslashes before non-ASCII chars in JSON string values. | #L983-L997 |
_sanitize_log_text |
function | _sanitize_log_text(value: object, limit: int \| None = None) -> str |
Escape control characters before logging untrusted text. | #L1000-L1022 |
_log_and_raise_internal_error |
function | _log_and_raise_internal_error(log_prefix: str, exc: Exception, detail: str) -> None |
Log a sanitized exception string and raise a generic 500 response. | #L1025-L1028 |
_raise_engine_busy |
function | _raise_engine_busy(exc: EngineBusy) -> None |
Translate serialized-engine admission failures into retryable HTTP 503. | #L1031-L1039 |
RequestModelContext |
class | RequestModelContext(model_name: str, engine: BaseEngine, lease: ModelLease \| None = None) |
Request-scoped engine/lease context. | #L1043-L1056 |
RequestModelContext.release |
method | async RequestModelContext.release() -> None |
Release the registry lease once, if this context owns one. | #L1050-L1056 |
_list_available_model_names |
function | _list_available_model_names() -> list[str] |
Function _list_available_model_names has 2 explicit return paths. |
#L1059-L1062 |
_response_model_name |
function | _response_model_name(request_model: str) -> str |
Return the response model field for single-model or registry mode. | #L1065-L1067 |
_acquire_request_model |
function | async _acquire_request_model(request_model: str) -> RequestModelContext |
Acquire the model/engine that should serve this request. | #L1070-L1094 |
_stream_with_model_context |
function | async _stream_with_model_context(context: RequestModelContext, stream: AsyncIterator[str]) -> AsyncIterator[str] |
Ensure model leases survive for the full streaming response. | #L1097-L1106 |
_build_tool_parser |
function | _build_tool_parser(engine: BaseEngine \| None) -> not annotated |
Create a fresh tool parser instance for a single request/stream. | #L1109-L1123 |
_build_reasoning_parser |
function | _build_reasoning_parser(engine: BaseEngine \| None = None) -> not annotated |
Create a fresh reasoning parser instance for a single request/stream. | #L1126-L1140 |
_prepare_streaming_reasoning_parser |
function | _prepare_streaming_reasoning_parser(engine: BaseEngine, request: ChatCompletionRequest \| ResponsesRequest \| None, chat_kwargs: dict[str, object], *, allowed: bool = True) -> not annotated |
Build and reset request-local reasoning state when thinking is enabled. | #L1143-L1156 |
_prepare_openai_stream_reasoning_state |
function | _prepare_openai_stream_reasoning_state(engine: BaseEngine, request: ChatCompletionRequest, chat_kwargs: dict[str, object]) -> tuple[object \| None, bool] |
Return request-local reasoning state and the legacy Nemotron marker state. | #L1159-L1171 |
_request_tool_definitions |
function | _request_tool_definitions(request: ChatCompletionRequest) -> list \| None |
Return the request tool schema once for streaming argument coercion. | #L1174-L1178 |
_streaming_json_fence_stripper |
function | _streaming_json_fence_stripper(request: ChatCompletionRequest) -> StreamingJsonFenceStripper \| None |
Create a fence stripper only for JSON-constrained streaming responses. | #L1181-L1191 |
_get_idle_unload_event |
function | _get_idle_unload_event() -> asyncio.Event |
Return the idle-unload gate event, creating it on first use. | #L1206-L1217 |
_invalidate_tool_parser_cache |
function | _invalidate_tool_parser_cache(reason: str \| None = None) -> None |
Drop cached parser state when the serving tokenizer changes. | #L1220-L1229 |
_load_prefix_cache_from_disk |
function | _load_prefix_cache_from_disk(engine: BaseEngine \| None = None) -> None |
Load prefix cache from disk during startup. | #L1232-L1250 |
_save_prefix_cache_to_disk |
function | _save_prefix_cache_to_disk(engine: BaseEngine \| None = None) -> None |
Save prefix cache to disk during shutdown. | #L1253-L1271 |
_get_cache_dir |
function | _get_cache_dir() -> str |
Get cache persistence directory based on actual model path. | #L1274-L1290 |
_build_engine |
function | _build_engine(spec: ModelSpec) -> BaseEngine |
Construct an engine instance from a model spec without starting it. | #L1293-L1323 |
_engine_factory |
function | async _engine_factory(spec: ModelSpec) -> BaseEngine |
Async engine factory used by the residency manager. | #L1326-L1328 |
_run_blocking_engine_cache_io |
function | async _run_blocking_engine_cache_io(io_fn, engine: BaseEngine) -> None |
Run blocking cache persistence off the event loop. | #L1331-L1350 |
_restore_engine_state |
function | async _restore_engine_state(spec: ModelSpec, engine: BaseEngine) -> None |
Restore engine-local state, such as prefix cache, after a cold load. | #L1353-L1356 |
_persist_engine_state |
function | async _persist_engine_state(spec: ModelSpec, engine: BaseEngine) -> None |
Persist engine-local state before an idle unload or shutdown unload. | #L1359-L1362 |
_activate_engine |
function | _activate_engine(engine: BaseEngine \| None) -> BaseEngine \| None |
Set the global engine pointer and refresh parser-sensitive state. | #L1365-L1375 |
_sync_engine_from_residency |
function | _sync_engine_from_residency() -> BaseEngine \| None |
Sync the global engine pointer from the residency manager state. | #L1378-L1388 |
_get_lifecycle_status |
function | _get_lifecycle_status() -> dict \| None |
Get lifecycle status for the default resident if lifecycle is enabled. | #L1391-L1395 |
_public_lifecycle_status |
function | _public_lifecycle_status(lifecycle: dict \| None) -> dict \| None |
Return residency status safe for unauthenticated public endpoints. | #L1398-L1410 |
_lifecycle_loop |
function | async _lifecycle_loop() -> None |
Background idle-unload loop for the default resident. | #L1413-L1433 |
_acquire_default_engine |
function | async _acquire_default_engine(*, count_activity: bool = True) -> BaseEngine |
Acquire the default engine, auto-loading via the residency manager if needed. | #L1436-L1451 |
_release_default_engine |
function | async _release_default_engine(*, count_activity: bool = True) -> None |
Release the default engine after request processing. | #L1454-L1463 |
lifespan |
function | async lifespan(app: FastAPI) -> not annotated |
FastAPI lifespan for startup/shutdown events. | #L1466-L1589 |
_metrics_result_from_status |
function | _metrics_result_from_status(status_code: int) -> str |
Map HTTP-ish status codes to low-cardinality inference results. | #L1602-L1610 |
_metrics_path_for_request |
function | _metrics_path_for_request(request: Request) -> str |
Prefer route templates over raw URLs to keep metrics cardinality bounded. | #L1613-L1626 |
_metrics_middleware |
function | async _metrics_middleware(request: Request, call_next) -> not annotated |
Capture generic HTTP request metrics when enabled. | #L1630-L1659 |
RateLimiter |
class | RateLimiter(requests_per_minute: int = 60, enabled: bool = False) |
Simple in-memory rate limiter using sliding window. | #L1662-L1700 |
RateLimiter.__init__ |
method | RateLimiter.__init__(requests_per_minute: int = 60, enabled: bool = False) -> not annotated |
Method RateLimiter.__init__ updates self.requests_per_minute, self.enabled, self.window_size, self._requests; calls defaultdict, threading.Lock. |
#L1665-L1670 |
RateLimiter.is_allowed |
method | RateLimiter.is_allowed(client_id: str) -> tuple[bool, int] |
Check if request is allowed for client. | #L1672-L1700 |
check_rate_limit |
function | async check_rate_limit(request: Request) -> not annotated |
Rate limiting dependency. | #L1707-L1720 |
verify_api_key |
function | async verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)) -> not annotated |
Verify API key if authentication is enabled. | #L1723-L1742 |
get_engine |
function | get_engine() -> BaseEngine |
Get the loaded engine, raising error if not loaded. | #L1745-L1749 |
_coerce_tool_arguments |
function | _coerce_tool_arguments(arguments_json: str, tool_name: str, tools: list[dict] \| None) -> str |
Coerce tool call arguments to match the tool schema. | #L1752-L1796 |
_validate_model_name |
function | _validate_model_name(request_model: str) -> None |
Validate that the request model name matches the served model. | #L1799-L1818 |
_get_engine_tokenizer |
function | _get_engine_tokenizer(engine: BaseEngine \| None) -> object \| None |
Return tokenizer-like parser state from the active engine. | #L1821-L1828 |
_get_or_init_tool_parser |
function | _get_or_init_tool_parser(engine: BaseEngine \| None = None) -> not annotated |
Return the cached tool parser, initializing it from the given engine. | #L1831-L1841 |
_parse_tool_calls_with_parser |
function | _parse_tool_calls_with_parser(output_text: str, request: ChatCompletionRequest \| None = None, engine: BaseEngine \| None = None) -> tuple[str, list \| None] |
Parse tool calls from model output using the configured parser. | #L1844-L1930 |
_apply_response_format_or_raise |
function | _apply_response_format_or_raise(text: str, response_format: object, *, ensure_ascii: bool = False) -> str |
Return validated JSON content or fail before returning a success response. | #L1933-L1952 |
_response_format_type |
function | _response_format_type(response_format: object \| None) -> str \| None |
Function _response_format_type calls isinstance, response_format.get, getattr; has 3 explicit return paths. |
#L1955-L1960 |
_promote_streaming_response_format_delta |
function | _promote_streaming_response_format_delta(content: str \| None, reasoning: str \| None, request: ChatCompletionRequest) -> tuple[str \| None, str \| None] |
Keep response_format JSON on the streaming content channel. | #L1963-L1981 |
_new_response_item_id |
function | _new_response_item_id(prefix: str) -> str |
Generate stable OpenAI-style item ids. | #L1984-L1986 |
_response_content_to_text |
function | _response_content_to_text(content) -> str |
Normalize Responses API content items into plain text. | #L1989-L2006 |
_responses_tools_to_chat_tools |
function | _responses_tools_to_chat_tools(tools: list[ResponseFunctionTool \| dict]) -> tuple[list[dict] \| None, list[str]] |
Convert supported Responses tools and report unsupported tool types. | #L2009-L2049 |
_responses_input_to_chat_messages |
function | _responses_input_to_chat_messages(request: ResponsesRequest) -> list[dict] |
Convert Responses API input items into chat-completions-style messages. | #L2052-L2170 |
_responses_request_to_new_persisted_messages |
function | _responses_request_to_new_persisted_messages(request: ResponsesRequest) -> list[dict] |
Persist only the current request's replayable input items. | #L2173-L2181 |
_responses_request_to_persisted_messages |
function | _responses_request_to_persisted_messages(request: ResponsesRequest) -> list[dict] |
Persist replayable history for chained previous_response_id requests. | #L2184-L2200 |
_responses_request_to_chat_request |
function | _responses_request_to_chat_request(request: ResponsesRequest) -> ChatCompletionRequest |
Build a ChatCompletionRequest from a ResponsesRequest. | #L2203-L2253 |
_build_responses_output_items |
function | _build_responses_output_items(text: str \| None, reasoning: str \| None, tool_calls: list[ToolCall] \| None) -> list[ResponseMessageItem \| ResponseReasoningItem \| ResponseFunctionCallItem] |
Convert parsed assistant output into Responses API output items. | #L2256-L2293 |
_response_output_items_to_chat_messages |
function | _response_output_items_to_chat_messages(output_items: list) -> list[dict] |
Persist assistant output in chat-completions form for previous_response_id. | #L2296-L2325 |
_build_response_object |
function | _build_response_object(request: ResponsesRequest, output_items: list[ResponseMessageItem \| ResponseReasoningItem \| ResponseFunctionCallItem], prompt_tokens: int, completion_tokens: int, finish_reason: str \| None, response_id: str \| None = None) -> ResponseObject |
Build a full Responses API object. | #L2328-L2367 |
_prepare_responses_request |
function | _prepare_responses_request(request: ResponsesRequest, *, validate_remote_media: bool = True) -> tuple[BaseEngine, ChatCompletionRequest, list[dict], dict] |
Prepare a Responses request for execution on the chat engine. | #L2370-L2414 |
_prepare_streaming_responses_request |
function | _prepare_streaming_responses_request(request: ResponsesRequest) -> tuple[BaseEngine, ChatCompletionRequest, list[dict], dict] |
Prepare a streaming Responses request after eager URL validation. | #L2417-L2421 |
_run_responses_request |
function | async _run_responses_request(request: ResponsesRequest, raw_request: Request) -> tuple[ResponseObject \| None, list[dict]] |
Execute a Responses API request against the backend chat engine. | #L2424-L2477 |
_stream_responses_request |
function | async _stream_responses_request(request: ResponsesRequest) -> AsyncIterator[str] |
Execute a Responses API request and stream SSE events incrementally. | #L2480-L2868 |
_stream_responses_request._start_text_item |
nested function | _stream_responses_request._start_text_item() -> list[str] |
Nested Function _stream_responses_request._start_text_item calls _new_response_item_id, events.append, _responses_sse_event, ResponseOutputItemAddedEvent; returns events. |
#L2525-L2561 |
_stream_responses_request._start_reasoning_item |
nested function | _stream_responses_request._start_reasoning_item() -> list[str] |
Nested Function _stream_responses_request._start_reasoning_item calls _new_response_item_id, events.append, _responses_sse_event, ResponseOutputItemAddedEvent; returns events. |
#L2563-L2598 |
_responses_sse_event |
function | _responses_sse_event(event_type: str, payload: BaseModel \| dict) -> str |
Encode a Responses API SSE event. | #L2871-L2878 |
_strip_harmony_analysis_blocks |
function | _strip_harmony_analysis_blocks(text: str) -> str |
Remove harmony analysis-channel blocks (and their content) so reasoning text is never handed to the tool parser, while commentary/final text is preserved. | #L2888-L2892 |
_extract_reasoning_and_tool_calls |
function | _extract_reasoning_and_tool_calls(output_text: str, request: ChatCompletionRequest \| None = None, *, allow_reasoning: bool = True, engine: BaseEngine \| None = None) -> tuple[str \| None, str \| None, list[ToolCall] \| None] |
Extract reasoning first, then parse tool calls from the cleaned content. | #L2895-L2951 |
_detect_native_tool_support |
function | _detect_native_tool_support() -> bool |
Detect if the active tool parser supports native tool format. | #L2954-L2983 |
_detect_harmony_rendering |
function | _detect_harmony_rendering() -> bool |
Detect whether the harmony rendering path should handle prompt building. | #L2986-L3019 |
_tool_choice_disabled |
function | _tool_choice_disabled(request: ChatCompletionRequest \| None) -> bool |
Return True when tool_choice explicitly disables tool calling. | #L3022-L3031 |
_get_streaming_tool_parser |
function | _get_streaming_tool_parser(request: ChatCompletionRequest \| None, engine: BaseEngine \| None = None) -> not annotated |
Get a streaming-capable tool parser for this request. | #L3034-L3071 |
_extract_streaming_tool_delta |
function | _extract_streaming_tool_delta(parser, previous_text: str, delta_text: str, request_context: dict) -> tuple[str, dict \| None] |
Parse one request-local streaming delta and return new accumulated text. | #L3074-L3088 |
_stream_request_metadata |
function | _stream_request_metadata(request: ChatCompletionRequest) -> tuple[dict, list \| None, bool] |
Function _stream_request_metadata calls request.model_dump(include={'tools'}).get, request.model_dump, bool; returns ({'tools': tools or []}, tools, include_usage). |
#L3091-L3100 |
_parse_streaming_tool_content |
function | _parse_streaming_tool_content(parser, accumulated_text: str, delta_text: str, request_context: dict) -> tuple[str, dict \| None, bool] |
Function _parse_streaming_tool_content calls _extract_streaming_tool_delta; returns (accumulated_text, result, suppress). |
#L3103-L3116 |
_streaming_tool_markup_possible |
function | _streaming_tool_markup_possible(text: str) -> bool |
Heuristic marker check to avoid parser work on ordinary text chunks. | #L3119-L3125 |
_streaming_tool_markup_possible_after_delta |
function | _streaming_tool_markup_possible_after_delta(accumulated_text: str, delta_text: str) -> bool |
Check only the boundary window needed to detect newly appearing tool markup. | #L3128-L3143 |
load_embedding_model |
function | load_embedding_model(model_name: str \| None, *, lock: bool = False, reuse_existing: bool = True) -> None |
Load or reuse the embedding model engine when configured. | #L3146-L3171 |
load_reranker_model |
function | load_reranker_model(model_name: str \| None, *, lock: bool = False, reuse_existing: bool = True) -> None |
Load or reuse the reranker model engine when configured. | #L3174-L3199 |
load_model |
function | load_model(model_name: str, use_batching: bool = False, scheduler_config = None, stream_interval: int = 1, max_tokens: int = 32768, max_request_tokens: int = 32768, force_mllm: bool = False, gpu_memory_utilization: float = 0.9, served_model_name: str \| None = None, trust_remote_code: bool = False, mtp: bool = False, prefill_step_size: int = 2048, specprefill_enabled: bool = False, specprefill_threshold: int = 8192, specprefill_keep_pct: float = 0.3, specprefill_backbone_pct: float = 0.0, specprefill_draft_model: str = None, mllm_draft_model: str \| None = None, mllm_draft_kind: str \| None = None, mllm_draft_block_size: int \| None = None, warm_prompts_path: str \| None = None, auto_unload_idle_seconds: float = 0.0, lazy_load_model: bool = False) -> not annotated |
Load a model (auto-detects MLLM vs LLM). | #L3202-L3431 |
load_model_registry |
function | load_model_registry(config_path: str, *, defaults: RegistryServeDefaults) -> None |
Load a registry-backed model manager from YAML configuration. | #L3434-L3457 |
get_usage |
function | get_usage(output: GenerationOutput) -> Usage |
Extract usage metrics from GenerationOutput. | #L3460-L3472 |
metrics |
function | async metrics() -> not annotated |
Prometheus scrape endpoint (disabled by default). | #L3476-L3485 |
health |
function | async health() -> not annotated |
Health check endpoint. | #L3489-L3544 |
status |
function | async status() -> not annotated |
Real-time status with per-request details for debugging and monitoring. | #L3548-L3597 |
cache_stats |
function | async cache_stats() -> not annotated |
Get cache statistics for debugging and monitoring. | #L3601-L3627 |
clear_cache |
function | async clear_cache() -> not annotated |
Clear all caches. | #L3631-L3659 |
clear_prefix_cache |
function | async clear_prefix_cache() -> not annotated |
Clear the text prefix cache used for KV reuse in continuous batching. | #L3663-L3713 |
clear_prefix_cache._rewarm |
nested function | async clear_prefix_cache._rewarm() -> not annotated |
Nested Function clear_prefix_cache._rewarm calls load_warmup_file, warm_prefix_cache, logger.info, logger.warning; awaits asynchronous work. |
#L3688-L3707 |
cancel_request |
function | async cancel_request(request_id: str) -> not annotated |
Cancel an active or queued request. | #L3720-L3747 |
delete_request |
function | async delete_request(request_id: str) -> not annotated |
OpenAI-style alias for cancelling an active or queued request. | #L3754-L3756 |
list_models |
function | async list_models() -> ModelsResponse |
List available models. | #L3760-L3775 |
create_embeddings |
function | async create_embeddings(request: EmbeddingRequest) -> EmbeddingResponse |
Create embeddings for the given input text(s). | #L3787-L3908 |
rerank_documents |
function | async rerank_documents(request: RerankRequest) -> RerankResponse |
Rerank documents against a query using a cross-encoder model. | #L3920-L4038 |
list_mcp_tools |
function | async list_mcp_tools() -> MCPToolsResponse |
List all available MCP tools. | #L4047-L4063 |
list_mcp_servers |
function | async list_mcp_servers() -> MCPServersResponse |
Get status of all MCP servers. | #L4067-L4084 |
execute_mcp_tool |
function | async execute_mcp_tool(request: MCPExecuteRequest) -> MCPExecuteResponse |
Execute an MCP tool. | #L4088-L4117 |
create_transcription |
function | async create_transcription(file: UploadFile, model: str = 'whisper-large-v3', language: str \| None = None, response_format: str = 'json') -> not annotated |
Transcribe audio to text (OpenAI Whisper API compatible). | #L4130-L4196 |
create_speech |
function | async create_speech(model: str = 'kokoro', input: str = '', voice: str = 'af_heart', speed: float = 1.0, response_format: str = 'wav') -> not annotated |
Generate speech from text (OpenAI TTS API compatible). | #L4200-L4254 |
list_voices |
function | async list_voices(model: str = 'kokoro') -> not annotated |
List available voices for a TTS model. | #L4258-L4267 |
_ensure_sse_terminal |
function | async _ensure_sse_terminal(generator: AsyncIterator[str], terminal_frame: str) -> AsyncIterator[str] |
Guarantee that terminal_frame is emitted exactly once at the end of generator, even if the generator raises mid-stream. | #L4275-L4296 |
_find_uvicorn_cycle |
function | _find_uvicorn_cycle(obj, depth = 0, visited = None) -> not annotated |
Walk through middleware wrappers to find uvicorn's RequestResponseCycle. | #L4299-L4346 |
_is_client_disconnected |
function | _is_client_disconnected(raw_request: Request) -> bool |
Reliable client disconnect check. | #L4349-L4374 |
_disconnect_guard |
function | async _disconnect_guard(generator: AsyncIterator[str], raw_request: Request, poll_interval: float = 0.5, heartbeat_interval: float = 5.0, cleanup = None, timeout: float \| None = None) -> AsyncIterator[str] |
Wrap streaming generator to abort on client disconnect. | #L4377-L4546 |
_disconnect_guard._elapsed |
nested function | _disconnect_guard._elapsed() -> not annotated |
Nested Function _disconnect_guard._elapsed calls _time.monotonic; returns f'{_time.monotonic() - _t0:.1f}s'. |
#L4407-L4408 |
_disconnect_guard._wait_disconnect |
nested function | async _disconnect_guard._wait_disconnect() -> not annotated |
Nested Function _disconnect_guard._wait_disconnect calls asyncio.sleep, _is_client_disconnected, logger.info, _elapsed; awaits asynchronous work; returns None. |
#L4417-L4429 |
_disconnect_guard._deferred_generator_close |
nested function | async _disconnect_guard._deferred_generator_close() -> not annotated |
Nested Function _disconnect_guard._deferred_generator_close calls asyncio.sleep, _gen_to_close.aclose, logger.debug, type; awaits asynchronous work. |
#L4528-L4536 |
_wait_with_disconnect |
function | async _wait_with_disconnect(coro, raw_request: Request, timeout: float, poll_interval: float = 0.5, timeout_detail_seconds: float \| None = None, cleanup_result = None) -> not annotated |
Run a coroutine with both timeout and client disconnect detection. | #L4549-L4638 |
_wait_with_disconnect._wait_disconnect |
nested function | async _wait_with_disconnect._wait_disconnect() -> not annotated |
Nested Function _wait_with_disconnect._wait_disconnect calls asyncio.sleep, _is_client_disconnected, logger.info, _time.monotonic; awaits asynchronous work; returns None. |
#L4569-L4581 |
_start_request_budget |
function | _start_request_budget(timeout: float \| None) -> tuple[float, float] |
Return the total timeout and absolute deadline for a request. | #L4641-L4644 |
_remaining_request_timeout |
function | _remaining_request_timeout(total_timeout: float, deadline: float) -> float |
Compute remaining request budget or raise the standard timeout error. | #L4647-L4655 |
_acquire_default_engine_for_request |
function | async _acquire_default_engine_for_request(raw_request: Request, *, total_timeout: float, deadline: float, count_activity: bool = True, model: str \| None = None) -> BaseEngine \| None |
Acquire the engine for a request, using the model registry when active. | #L4661-L4719 |
_acquire_default_engine_for_request._registry_acquire |
nested function | async _acquire_default_engine_for_request._registry_acquire() -> not annotated |
Nested Function _acquire_default_engine_for_request._registry_acquire calls _acquire_request_model, id; awaits asynchronous work; returns ctx.engine. |
#L4681-L4685 |
_acquire_default_engine_for_request._registry_cleanup |
nested function | async _acquire_default_engine_for_request._registry_cleanup(_result) -> not annotated |
Nested Function _acquire_default_engine_for_request._registry_cleanup calls _active_request_contexts.pop, id, ctx.release; awaits asynchronous work. |
#L4687-L4690 |
_release_engine_for_request |
function | async _release_engine_for_request(raw_request: Request \| None, *, count_activity: bool = True) -> None |
Release the engine acquired for this request. | #L4722-L4737 |
_make_release_cleanup |
function | _make_release_cleanup(raw_request: Request \| None) -> not annotated |
Return a cleanup callable suitable for _disconnect_guard. |
#L4740-L4752 |
_make_release_cleanup._cleanup |
nested function | async _make_release_cleanup._cleanup() -> not annotated |
Nested Function _make_release_cleanup._cleanup calls _active_request_contexts.pop, id, ctx.release, _release_default_engine; awaits asynchronous work. |
#L4744-L4749 |
create_completion |
function | async create_completion(request: CompletionRequest, raw_request: Request) -> not annotated |
Create a text completion. | #L4763-L4909 |
create_chat_completion |
function | async create_chat_completion(request: ChatCompletionRequest, raw_request: Request) -> not annotated |
Create a chat completion (supports multimodal content for VLM models). | #L4916-L5114 |
_normalize_messages |
function | _normalize_messages(messages: list[dict]) -> list[dict] |
Normalize message roles and merge consecutive same-role messages. | #L5117-L5172 |
_get_engine_tokenizer |
function | _get_engine_tokenizer(engine) -> object \| None |
Return the tokenizer backing engine, if exposed. |
#L5175-L5187 |
create_response |
function | async create_response(request: ResponsesRequest, raw_request: Request) -> not annotated |
Create a Responses API response. | #L5194-L5214 |
_get_forced_tool_name |
function | _get_forced_tool_name(tool_choice) -> str \| None |
Extract forced tool name from tool_choice, if any. | #L5217-L5230 |
_apply_forced_tool_choice |
function | _apply_forced_tool_choice(tool_choice, tools, messages, chat_kwargs = None) -> not annotated |
Apply forced tool_choice by filtering tools and injecting instructions. | #L5233-L5279 |
_tool_name |
function | _tool_name(tool: dict) -> str \| None |
Extract function name from a tool definition dict. | #L5282-L5287 |
_inject_json_instruction |
function | _inject_json_instruction(messages: list, instruction: str) -> list |
Inject JSON instruction into messages. | #L5290-L5319 |
_convert_anthropic_stop_reason |
function | _convert_anthropic_stop_reason(openai_reason: str \| None) -> str |
Convert OpenAI finish_reason to Anthropic stop_reason. | #L5327-L5335 |
_prepare_anthropic_endpoint_invocation |
function | _prepare_anthropic_endpoint_invocation(engine: BaseEngine, openai_request: ChatCompletionRequest, effective_max_tokens: int) -> PreparedChatInvocation |
Prepare Anthropic invocation and convert URL-safety errors to 400s. | #L5338-L5351 |
create_anthropic_message |
function | async create_anthropic_message(request: Request) -> not annotated |
Anthropic Messages API endpoint. | #L5357-L5578 |
count_anthropic_tokens |
function | async count_anthropic_tokens(request: Request) -> not annotated |
Count tokens for an Anthropic Messages API request. | #L5585-L5666 |
_emit_content_pieces |
function | _emit_content_pieces(pieces: list[tuple[str, str]], current_block_type: str \| None, block_index: int) -> tuple[list[str], str \| None, int] |
Emit Anthropic SSE events for content pieces from the think router. | #L5669-L5719 |
_stream_anthropic_messages |
function | async _stream_anthropic_messages(engine: BaseEngine, openai_request: ChatCompletionRequest, anthropic_request: AnthropicRequest, prepared: PreparedChatInvocation, metrics_tracker = None) -> AsyncIterator[str] |
Stream Anthropic Messages API SSE events. | #L5722-L5995 |
stream_completion |
function | async stream_completion(engine: BaseEngine, prompt: str, request: CompletionRequest, max_tokens: int, repetition_penalty: float \| None = None, metrics_tracker = None) -> AsyncIterator[str] |
Stream completion response. | #L6003-L6084 |
stream_chat_completion |
function | async stream_chat_completion(engine: BaseEngine, messages: list, request: ChatCompletionRequest, metrics_tracker = None, **kwargs) -> AsyncIterator[str] |
Stream chat completion response. | #L6087-L6512 |
init_mcp |
function | async init_mcp(config_path: str) -> not annotated |
Initialize MCP manager from config file. | #L6520-L6546 |
_make_keepalive_http_protocol |
function | _make_keepalive_http_protocol(idle = 10, interval = 5, count = 3) -> not annotated |
Create a uvicorn HTTP protocol class with aggressive TCP keepalive. | #L6554-L6589 |
_make_keepalive_http_protocol._KeepaliveProtocol |
nested class | _make_keepalive_http_protocol._KeepaliveProtocol() |
Nested Class _make_keepalive_http_protocol._KeepaliveProtocol derives from _Base and declares 1 direct member(s). |
#L6567-L6587 |
_make_keepalive_http_protocol._KeepaliveProtocol.connection_made |
nested function | _make_keepalive_http_protocol._KeepaliveProtocol.connection_made(transport) -> not annotated |
Nested Function _make_keepalive_http_protocol._KeepaliveProtocol.connection_made calls super().connection_made, super, transport.get_extra_info, sock.setsockopt; returns None. |
#L6568-L6587 |
main |
function | main() -> not annotated |
Run the server. | #L6597-L6708 |
create_parser |
function | create_parser() -> argparse.ArgumentParser |
Create the standalone server CLI parser. | #L6711-L6912 |