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 | |
from_yaml
classmethod
Load configuration from a YAML file.
Mirrors :meth:llm.training.core.config.Config.from_yaml — keeps the
training-side and serving-side config loading surfaces symmetric so
users can pick whichever input style fits their workflow (YAML files
vs. environment variables).
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
|
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
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
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 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 | |
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
stream_request
Run a request to completion, yielding decoded text chunks.
源代码位于: src/llm/serving/batch_engine.py
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).
Bookend the model forward with lock acquire/release: lock for pre-compute (slot allocation, prefix-cache lookup, batch tensor construction), release for the forward, re-acquire for post-compute (append tokens, free slots, mark finished). The forward is the expensive part; freeing the lock around it lets other worker threads enqueue / dequeue requests in parallel.
返回:
| 类型 | 描述 |
|---|---|
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.
返回:
| 类型 | 描述 |
|---|---|
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
Scheduler
scheduler
Scheduler
A simple First-Come-First-Serve (FCFS) scheduler for continuous batching.
源代码位于: src/llm/serving/scheduler.py
add_sequence
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
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 | |
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 with the request_id so operators can correlate. The envelope does NOT leak internal details to clients.
源代码位于: 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
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.
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
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 | |
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
health
Health and readiness endpoints.
health_check
async
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.
源代码位于: src/llm/serving/loader.py
infer_vocab_size
Infer vocabulary size from an LM head or embedding weight tensor.
源代码位于: 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.