llm.serving — FastAPI Application¶
REST + OpenAI-compatible chat-completions API. Boot the server with
uv run llm-serve or uv run uvicorn llm.serving.api:app.
Application Factory¶
api
¶
FastAPI application factory for the serving API.
This module wires the pieces together:
- :class:
RequestIDMiddleware(request correlation + access log) - exception handlers that map every failure to the structured envelope
in :mod:
llm.serving.errors - the three routers (health, generate, chat)
- :class:
prometheus_fastapi_instrumentator.Instrumentator
All endpoint logic lives in the routers; this file stays focused on process wiring (logging setup, lifespan, app construction) so adding a new endpoint doesn't grow it.
get_api_key
async
¶
get_api_key(api_key_header_value=Security(api_key_header), auth_header=Security(authorization_header))
Verify the API key from X-API-Key or Authorization: Bearer.
Comparison uses hmac.compare_digest to avoid leaking key bytes via
timing. If the module-level config.api_key is unset, auth is
disabled and the function returns None (the public-host guard in
:mod:llm.serving.cli blocks starting the server on a non-loopback
interface without auth).
源代码位于: src/llm/serving/auth.py
is_loopback
¶
Return True if host is a loopback address.
Covers 127.0.0.0/8 and ::1. Anything else (0.0.0.0, *,
LAN IPs, public hostnames) is treated as non-loopback.
源代码位于: src/llm/serving/auth.py
lifespan
async
¶
FastAPI lifespan manager — load model, wire routers, log config.
源代码位于: src/llm/serving/api.py
Configuration¶
config
¶
ServingConfig
¶
Bases: BaseSettings
Serving Configuration using environment variables.
源代码位于: src/llm/serving/config.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
from_yaml
classmethod
¶
Load configuration from a YAML file.
Shaped after :meth:llm.training.core.config.Config.from_yaml, with
one deliberate divergence (RIL DEC-106): a missing file returns the
default :class:ServingConfig (llm-serve treats an absent config
as "all defaults"), whereas the training side raises
FileNotFoundError on a missing --config-path (an explicit path
is always a user error there). Both behaviours are pinned by tests.
The YAML keys are the unprefixed field names (api_key,
model_path, peft_method, ...). The same config can be set
via env vars (LLM_SERVING_API_KEY, LLM_SERVING_MODEL_PATH,
LLM_SERVING_PEFT_METHOD, ...).
返回:
| 名称 | 类型 | 描述 |
|---|---|---|
A |
ServingConfig
|
class: |
ServingConfig
|
or the default config when the path does not exist. |
|
ServingConfig
|
Validators ( |
|
ServingConfig
|
run on construction, so unknown PEFT methods and |
|
ServingConfig
|
inconsistent |
源代码位于: src/llm/serving/config.py
Continuous Batching Engine¶
batch_engine
¶
StepStats
dataclass
¶
Per-step stats returned by :meth:ContinuousBatchingEngine.step.
scheduled is the number of sequences that ran a forward pass in
the step (a.k.a. effective batch size). total_active_slots is the
engine's full slot pool — used as the denominator for the
llm_batch_fill_ratio Prometheus gauge.
源代码位于: src/llm/serving/batch_engine.py
SlotPrefixCache
¶
Maps token prefixes to KV cache slots for reuse across requests.
源代码位于: src/llm/serving/batch_engine.py
invalidate_for_slot
¶
Drop every prefix entry that points at slot.
When a sequence finishes, its KV slot returns to the free pool and a later request may be allocated the same slot, overwriting the cached K/V. If the stale prefix entry were left in place, a later request with the same prompt would hit the cache and replay another request's (now-overwritten or in-flight) K/V as its own prefix — a use-after-free of the cached KV. Entries are removed rather than re-pointed so the most-recent-usage ordering is unaffected for the remaining prefixes.
源代码位于: src/llm/serving/batch_engine.py
SlotAllocator
¶
Manages allocation of KV cache slots.
源代码位于: src/llm/serving/batch_engine.py
ContinuousBatchingEngine
¶
Inference engine supporting continuous batching (iteration-level scheduling).
This is the primary serving engine. It manages request states, schedules sequences at an iteration level, and orchestrates the forward pass.
源代码位于: src/llm/serving/batch_engine.py
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 | |
from_serving_config
classmethod
¶
Build an engine from ServingConfig flags.
Paged Attention is fully wired through the continuous batching
forward path (docs/adr/004-paged-attention-serving.md was
flipped to "Accepted" with this slice). When
config.use_paged_attention=True the engine builds a
:class:PagedKVCache, passes it to the model forward, and
frees per-request blocks on sequence completion.
源代码位于: src/llm/serving/batch_engine.py
add_request
¶
Add a request to the engine.
源代码位于: src/llm/serving/batch_engine.py
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | |
stream_request
¶
Run a request to completion, yielding decoded text chunks.
Honours stop sequences: when the accumulated generated text
(post-prompt) ends with any stop string, generation halts and the
stop string itself is excluded from the yielded output (OpenAI
semantics).
源代码位于: src/llm/serving/batch_engine.py
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 | |
generate_request
¶
Run a request to completion and return prompt + generated text.
batch_generate_requests
¶
Run multiple requests sequentially through the batching engine.
step
¶
Run one inference step (sync wrapper).
The whole step — pre-compute, model forward, post-compute — holds
self._step_lock so two concurrent step() calls can never both
run the forward against the same slots and append two tokens to the
same sequence from one logical step (a real corruption when the
batched backend serves concurrent HTTP requests from FastAPI's
threadpool). Holding the lock across the forward does NOT serialize
request enqueueing: :meth:add_request never takes the step lock, so
new requests still arrive in parallel. The forward is the only code
that mutates the KV caches / slot bookkeeping the post step reads, so
this is exactly what the lock needs to guard.
返回:
| 类型 | 描述 |
|---|---|
StepStats
|
class: |
StepStats
|
effective batch size; |
StepStats
|
full slot pool (denominator for |
源代码位于: src/llm/serving/batch_engine.py
step_async
async
¶
Run one inference step, yielding to the event loop during the forward.
Identical contract to :meth:step, but the model forward runs
in a worker thread via :func:asyncio.to_thread. The lock is
only held for the bookkeeping portions (pre + post). This lets
the FastAPI event loop keep processing I/O (other requests,
health checks, /metrics scrapes) while a forward pass runs.
.. warning::
On the PAGED path (paged_kv_cache set) the forward mutates the
block manager (allocation / extension / copy-on-write of shared
prefix blocks — RIL TASK-065) which is NOT thread-safe. Two
overlapping step_async calls would interleave those mutations
and corrupt the block table. Production serving uses the
synchronous :meth:step (which holds the lock across the whole
forward) via run_in_threadpool; callers that enable paged
attention + prefix caching must use :meth:step, not
step_async, until the cache is externally synchronized.
返回:
| 类型 | 描述 |
|---|---|
StepStats
|
class: |
源代码位于: src/llm/serving/batch_engine.py
set_step_observer
¶
Install or clear a per-step observer (used for metric publishing).
The callback runs at the end of every :meth:step call, under
self._step_lock, with the :class:StepStats for that step.
Pass None to remove a previously installed observer.
源代码位于: src/llm/serving/batch_engine.py
unload_model
¶
Release model, KV caches and all scheduler state.
Clears model weights, both legacy and paged KV caches, prefix cache, slot allocator mappings, and scheduler queues so that GPU memory is freed and the engine is reusable after this call.
源代码位于: src/llm/serving/batch_engine.py
Scheduler¶
scheduler
¶
Scheduler
¶
Simple FCFS scheduler for continuous batching with backpressure.
Limits the waiting queue to max_waiting to prevent unbounded
memory growth under load. When the queue is full, :meth:add_sequence
raises RuntimeError so callers can apply backpressure (HTTP 503).
Thread safety: every method that reads or mutates waiting /
running takes the scheduler's own :attr:_lock. The engine's
step() path calls :meth:schedule under the engine's
_step_lock, while streaming/backpressure paths call
:meth:add_sequence, :meth:get_sequence and :attr:has_pending_work
WITHOUT the engine lock — without a scheduler-internal lock those
concurrent popleft / iteration calls crashed with RuntimeError:
deque mutated during iteration under concurrent streaming (RIL
ISS-069). Lock ordering stays acyclic: schedule (engine lock →
scheduler lock) never nests the engine lock inside the scheduler lock.
源代码位于: src/llm/serving/scheduler.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
add_sequence
¶
Add a new sequence to the waiting queue.
引发:
| 类型 | 描述 |
|---|---|
RuntimeError
|
If the waiting queue is at capacity. |
源代码位于: src/llm/serving/scheduler.py
add_sequence_if_not_conflicting
¶
Add seq unless an ACTIVE sequence already occupies its request_id.
Guard for RIL ISS-123: two distinct requests sharing one client
request_id hash to the SAME KV slot (SlotAllocator keys slots by
request_id), so their K/V and generated tokens contaminate each other
and a free() by either returns the other's live slot to the pool.
The engine's internal double-add contract (generate_request ->
stream_request re-adding the SAME logical request so the reap loop
can remove every copy) stays intact: when an matches callback is
supplied, a duplicate whose content equals the active holder is
allowed (it is the same request re-added). By default (no callback)
ANY active duplicate is rejected.
Returns True when the sequence was enqueued, False when it was
rejected as a conflicting duplicate.
引发:
| 类型 | 描述 |
|---|---|
RuntimeError
|
If the waiting queue is at capacity. |
源代码位于: src/llm/serving/scheduler.py
schedule
¶
Schedule sequences for the next inference step. Promotes waiting sequences to running if there is capacity.
源代码位于: src/llm/serving/scheduler.py
get_sequence
¶
Find a sequence by its request_id.
源代码位于: src/llm/serving/scheduler.py
remove
¶
Drop a sequence from the waiting queue / running list.
Used by the streaming generator's cleanup path when the consumer
abandons mid-generation (RIL ISS-105): the abandoned generator is the
sequence's only stepper and can never advance it again, so leaving it
RUNNING permanently consumes a KV slot (schedule only filters
FINISHED). Idempotent: returns the removed sequence or None.
源代码位于: src/llm/serving/scheduler.py
Generation Service¶
generation_service
¶
Serving-side generation service backed by GenerationBackend.
ServingGenerationService
dataclass
¶
Shared generation entry point for REST and chat APIs.
源代码位于: src/llm/serving/generation_service.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |
Errors¶
errors
¶
Structured error envelope for the serving API (Finding K).
All endpoints in src/llm/serving raise APIError (or an HTTPException
that the global handler maps to an envelope). The envelope shape is::
{
"error": {
"code": "<stable_id>", # machine-readable, e.g. "invalid_request"
"message": "<human>", # one-line description
"details": {...}, # structured context (field-level errors, etc.)
"request_id": "<uuid>" # X-Request-ID echo
}
}
The HTTP status is set by the status_code field on APIError (or by
mapping ErrorCode to its default status). The X-Request-ID middleware
sets request.state.request_id and echoes it on the response header.
ErrorCode
¶
Bases: StrEnum
Stable machine-readable error identifiers.
These strings are part of the public API. Adding new codes is fine; renaming or removing them is a breaking change.
源代码位于: src/llm/serving/errors.py
APIError
¶
Bases: Exception
A typed error with a stable code, human message, and structured details.
Endpoints raise APIError instead of HTTPException. The global
exception handler installed in :mod:llm.serving.api converts it to
the standard envelope.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
code
|
ErrorCode | str
|
One of :class: |
必需 |
message
|
str
|
One-line human description. |
必需 |
status_code
|
int | None
|
HTTP status to return. Defaults to the canonical
status for |
None
|
details
|
dict[str, Any] | None
|
Optional structured context (e.g. field-level validation errors, retry-after seconds, etc.). |
None
|
源代码位于: src/llm/serving/errors.py
default_status_for
¶
to_envelope
¶
Build the canonical error envelope dict.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
code
|
str
|
Machine-readable error code (e.g. |
必需 |
message
|
str
|
One-line human description. |
必需 |
request_id
|
str
|
The X-Request-ID for this request. |
必需 |
details
|
dict[str, Any] | None
|
Optional structured context. |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
|
源代码位于: src/llm/serving/errors.py
envelope_from_http_exception
¶
Convert a fastapi.HTTPException to the envelope shape.
The detail field may be a string or a dict; we pass it through as
details so callers don't lose context.
源代码位于: src/llm/serving/errors.py
envelope_from_validation_error
¶
Convert a pydantic / FastAPI RequestValidationError to the envelope.
源代码位于: src/llm/serving/errors.py
envelope_from_api_error
¶
Convert an :class:APIError to the envelope shape.
源代码位于: src/llm/serving/errors.py
envelope_from_unexpected
¶
Convert an unexpected Exception to the envelope shape.
Logs the exception (class + traceback) with the request_id so operators
can correlate. The envelope does NOT leak internal details to clients —
not even the exception class name (RIL ISS-168): type(exc).__name__
previously let a client fingerprint the framework/backend from any 500
("RuntimeError", "CUDA error" classes, filesystem paths inside
backend str(exc) messages).
源代码位于: src/llm/serving/errors.py
get_request_id
¶
Return the request_id stored on the request state.
Falls back to "unknown" if the middleware hasn't run (which would
be a programming error in production — see
:class:llm.serving.middleware.RequestIDMiddleware).
源代码位于: src/llm/serving/errors.py
envelope_response
¶
Build the canonical JSON response: envelope body + X-Request-ID header.
源代码位于: src/llm/serving/errors.py
register_exception_handlers
¶
Wire the standard FastAPI exception handlers onto app.
All errors raised inside the serving API (typed :class:APIError,
FastAPI :class:HTTPException, pydantic validation errors, and
unexpected exceptions) flow through this single registration point
and come out shaped as :func:to_envelope.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
app
|
FastAPI
|
The :class: |
必需 |
logger
|
Any | None
|
Optional logger to receive unexpected exceptions. If
|
None
|
源代码位于: src/llm/serving/errors.py
Auth¶
auth
¶
Authentication for the serving API.
Currently a single shared API key compared in constant time
(hmac.compare_digest) to avoid timing leaks. Supports both
X-API-Key: <key> and Authorization: Bearer <key> headers.
A future multi-tenant extension can replace the body of :func:get_api_key
without changing call sites, as long as the return contract (the key on
success, raising :class:APIError with code unauthorized on failure)
is preserved.
get_api_key
async
¶
get_api_key(api_key_header_value=Security(api_key_header), auth_header=Security(authorization_header))
Verify the API key from X-API-Key or Authorization: Bearer.
Comparison uses hmac.compare_digest to avoid leaking key bytes via
timing. If the module-level config.api_key is unset, auth is
disabled and the function returns None (the public-host guard in
:mod:llm.serving.cli blocks starting the server on a non-loopback
interface without auth).
源代码位于: src/llm/serving/auth.py
is_loopback
¶
Return True if host is a loopback address.
Covers 127.0.0.0/8 and ::1. Anything else (0.0.0.0, *,
LAN IPs, public hostnames) is treated as non-loopback.
源代码位于: src/llm/serving/auth.py
assert_safe_bind
¶
Fail-closed guard: refuse to serve anonymously on a non-loopback bind.
The single home for the check every entry point validates — the
llm-serve CLI (:func:llm.serving.cli.main), the FastAPI lifespan
that the Docker image's direct uvicorn llm.serving.api:app launch
runs, etc. Because all of them now read the SAME host the server
actually binds (LLM_SERVING_HOST / ServingConfig.host), a
Docker/uvicorn launch that skipped the CLI can no longer bind
0.0.0.0 with api_key=None and serve instruction-generating
endpoints fully anonymously (RIL ISS-164). host=0.0.0.0 without
auth fails at startup rather than silently at runtime.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
host
|
str
|
The bind address the server will use. |
必需 |
api_key
|
str | None
|
The configured |
必需 |
source
|
str
|
Name used in the error message for context. |
'ServingConfig.host'
|
源代码位于: src/llm/serving/auth.py
Middleware¶
middleware
¶
ASGI middleware for the serving API.
Right now this holds the :class:RequestIDMiddleware, which assigns a
stable X-Request-ID to every request (honoring an inbound header),
echoes it on the response, and logs a structured access line per request
so operators can correlate uvicorn access logs with application logs.
RequestBodySizeLimit
¶
Pure-ASGI middleware rejecting request bodies over max_bytes.
Defense-in-depth for client memory-exhaustion DoS (RIL ISS-171): without
a limit, a single multi-hundred-MB JSON body (one giant prompt, many
chat messages) is fully buffered and tokenized. Two layers here:
- Content-Length fast reject — when the client declares a length
over the cap, respond
413 Payload Too Largebefore reading any body. - Incremental cap for chunked / unknown-length bodies — counts bytes
as the ASGI
http.requestmessages stream in and rejects as soon as the cap is crossed, discarding (never buffering) the remainder.
Implemented as raw ASGI (not :class:BaseHTTPMiddleware) so it wraps the
transport layer and does NOT interfere with SSE response streaming.
源代码位于: src/llm/serving/middleware.py
RequestIDMiddleware
¶
Bases: BaseHTTPMiddleware
Assign, propagate, and log X-Request-ID for every request.
Behavior:
- If the client sent X-Request-ID, reuse it (so callers can stitch
retries to a single trace).
- Otherwise, generate a new UUID4 hex.
- Store on request.state.request_id so handlers and exception
handlers can include it in error envelopes.
- Echo on the response X-Request-ID header.
- Log a structured INFO line on response (method, path, status,
duration_ms, request_id).
源代码位于: src/llm/serving/middleware.py
Custom Prometheus Metrics¶
metrics
¶
Custom Prometheus metrics for the serving API (Finding AX, T2 #22).
prometheus-fastapi-instrumentator already gives generic HTTP RED
metrics (rate, errors, duration) per route. Domain-specific signals —
tokens generated per request, batch fill ratio, KV-cache hit rate,
queue depth — are not visible to operators without these counters.
Layout¶
:class:ServingMetrics is a thin container around a CollectorRegistry
that holds the six metrics required by the audit ticket. The module
also exposes a module-level :data:METRICS singleton wired into the
default Prometheus registry so :func:prometheus_fastapi_instrumentator.Instrumentator.expose
makes them visible at /metrics.
Usage¶
::
from llm.serving.metrics import METRICS
with METRICS.request_timer(endpoint="generate") as timer:
async with METRICS.track_inflight():
text = await run_in_threadpool(_sync_generate, ...)
METRICS.observe_tokens(endpoint="generate", token_count=len(text))
timer.set_status(200)
The engine can publish per-step stats via :func:ServingMetrics.record_batch_fill_ratio,
called from the on_step hook passed to
:class:~llm.serving.batch_engine.ContinuousBatchingEngine.
ServingMetrics
¶
Container for the serving tier's domain Prometheus metrics.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
registry
|
CollectorRegistry | None
|
The Prometheus registry to register metrics against.
Defaults to the module-level default (:data: |
None
|
源代码位于: src/llm/serving/metrics.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
observe_tokens
¶
Record one request's completion token count.
Bumps both the cumulative counter and the per-request histogram so dashboards can show throughput and p95 in one set of queries.
源代码位于: src/llm/serving/metrics.py
record_batch_fill_ratio
¶
Update llm_batch_fill_ratio from a step() result.
total_active_slots is the engine's full slot pool; scheduled
is how many of those were used in the most recent step. Callers
passing total_active_slots=0 get a ValueError because the
ratio is undefined (engine not yet initialized).
源代码位于: src/llm/serving/metrics.py
record_kv_cache_hit_ratio
¶
Update llm_kv_cache_hit_ratio. ratio must be in [0, 1].
源代码位于: src/llm/serving/metrics.py
track_inflight
¶
Context manager that inc/dec llm_inflight_requests.
Use to wrap the section of a request that holds an inference
slot (typically async with inference_semaphore). Decrement
runs even on exception so the gauge never sticks above zero.
源代码位于: src/llm/serving/metrics.py
request_timer
¶
Return a context manager that times a request and labels by status.
Use :meth:_RequestTimer.set_status before exiting to record the
HTTP status; the default is "error" so a missing call still
emits a labelled observation.
源代码位于: src/llm/serving/metrics.py
Chat Template¶
chat_template
¶
Render OpenAI-style chat messages into a single prompt string.
This is intentionally tiny and dependency-free so the serving tier stays
out of the tokenizer's way. The model is expected to have been trained on
the rendered format (or one configured via ServingConfig).
messages_to_prompt
¶
Convert chat messages to a single prompt string.
Each message is rendered with message_template.format(role=..., content=...)
(default: "{role}: {content}"). The rendered messages are joined
with newlines and generation_prefix (default: "Assistant: ") is
appended so the model knows where to start producing assistant tokens.
Override message_template and generation_prefix to match a
fine-tuned model's expected format (ChatML, Llama-2-chat, Vicuna, …).
源代码位于: src/llm/serving/chat_template.py
CLI¶
cli
¶
CLI entry point for the serving API.
reload=True is intentionally disabled because uvicorn's file-watcher
conflicts with from llm.serving.api import app (the watch import path
is incompatible with production use). For local development with auto-reload,
run uvicorn directly::
uvicorn llm.serving.api:app --reload --host 127.0.0.1 --port 8000
The function refuses to start when the server would bind to a non-loopback
address without an api_key configured. host=0.0.0.0 without auth
exposes the inference endpoint to the network; this guard makes that
mistake fail loudly at startup rather than silently at runtime.
main
¶
Entry point for the llm-serve CLI.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
config
|
ServingConfig | None
|
Optional pre-built :class: |
None
|
源代码位于: src/llm/serving/cli.py
Schemas¶
schemas
¶
RequestState
¶
Sequence
dataclass
¶
Internal representation of a sequence state for the engine.
源代码位于: src/llm/serving/schemas.py
GenerationRequest
¶
Bases: BaseModel
Generation request model.
源代码位于: src/llm/serving/schemas.py
GenerationResponse
¶
Bases: BaseModel
Generation response model.
源代码位于: src/llm/serving/schemas.py
BatchGenerationRequest
¶
Bases: BaseModel
Batch generation request model.
源代码位于: src/llm/serving/schemas.py
BatchGenerationResponse
¶
ChatMessage
¶
Bases: BaseModel
OpenAI-compatible chat message.
源代码位于: src/llm/serving/schemas.py
ChatCompletionRequest
¶
Bases: BaseModel
OpenAI-compatible chat completion request.
源代码位于: src/llm/serving/schemas.py
ChatCompletionUsage
¶
Bases: BaseModel
Token usage statistics.
源代码位于: src/llm/serving/schemas.py
ChatCompletionChoiceMessage
¶
ChatCompletionChoice
¶
Bases: BaseModel
A single completion choice.
源代码位于: src/llm/serving/schemas.py
ChatCompletionResponse
¶
Bases: BaseModel
OpenAI-compatible chat completion response.
源代码位于: src/llm/serving/schemas.py
ChatCompletionChunkDelta
¶
ChatCompletionChunkChoice
¶
Bases: BaseModel
A choice in a streaming chunk.
源代码位于: src/llm/serving/schemas.py
ChatCompletionChunk
¶
Bases: BaseModel
OpenAI-compatible streaming chunk.
源代码位于: src/llm/serving/schemas.py
Routers¶
chat
¶
OpenAI-compatible chat completions endpoint.
configure
¶
Bind the module-level config reference, semaphore, and metrics.
Called during lifespan startup.
源代码位于: src/llm/serving/routers/chat.py
chat_completions
async
¶
OpenAI-compatible chat completions endpoint.
源代码位于: src/llm/serving/routers/chat.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
generate
¶
Text generation endpoints (/generate, /batch_generate).
configure
¶
Bind the module-level references.
Called once during FastAPI lifespan startup. Importing this module
without configuring first will yield None values and the endpoints
will refuse to serve (the RuntimeError below is a programming
error, not a runtime condition).
源代码位于: src/llm/serving/routers/generate.py
generate_text
async
¶
Generate text from a single prompt. Supports streaming and non-streaming.
源代码位于: src/llm/serving/routers/generate.py
batch_generate_text
async
¶
Generate text for a batch of prompts in one call.
源代码位于: src/llm/serving/routers/generate.py
Model Loader¶
loader
¶
Load models and tokenizers for inference serving.
TrainingCheckpoint
dataclass
¶
Minimal view of a training checkpoint file.
源代码位于: src/llm/serving/loader.py
load_training_checkpoint
¶
Load a training checkpoint produced by CheckpointManager.
Accepts both the v2 split layout (<stem>.safetensors +
<stem>.meta.json + <stem>.extra_state.pt, the modern
CheckpointManager format) and the legacy v0.0.5 single-file
.pt blob, plus the bare nn.Module pickle emitted by
llm-quantize (a quantized model with GPTQQuantizedLinear /
AWQQuantizedLinear / SmoothQuantLinear submodules whose
per-layer quantization parameters live on the module instances).
path may be a stem, any of the three v2 sidecar paths, or a
legacy .pt path.
源代码位于: src/llm/serving/loader.py
infer_vocab_size
¶
Infer vocabulary size from an LM head or embedding weight tensor.
The embedding fallback key was a misspelling (embedding.token_embedding
vs the real embedding_layer.token_embeddings), making the branch
unreachable — a config-less tied-embedding checkpoint (no
lm_head.weight, per llm.compat.weight_mapping) wrongly raised
Cannot infer vocab_size even though the embedding tensor was present
and loadable (RIL ISS-167).
源代码位于: src/llm/serving/loader.py
infer_num_layers
¶
Count transformer blocks present in a state dict.
源代码位于: src/llm/serving/loader.py
load_tokenizer
¶
Load tokenizer from config or fall back to a printable character tokenizer.
load_model_and_tokenizer
¶
Build model/tokenizer for serving, loading weights when model_path is set.
PEFT integration (T2 PEFT #49): if config.peft_method is set, the
loader applies the method to the freshly loaded base model and
(optionally) loads the sidecar from config.peft_adapter_path.
Without any PEFT fields, the loader behavior is unchanged.
The apply+load step is fail-loud: a missing or corrupt sidecar
raises FileNotFoundError / ValueError /
RuntimeError so the serving process refuses to start with a
partial config — better than silently serving the un-adapted base
model.