Skip to content

latent.serve.server

AgentServer — the FastAPI app that serves an AgentProtocol over the wire.

Four endpoints (ADR-002 D3): POST /stream (SSE), POST /invoke (buffered JSON InvokeResult for non-streaming callers), GET /healthz (process alive), GET /readyz (registered + can serve). Both POST handlers share one pipeline: authenticate before any agent work (ADR-009 D1/NFR-3), construct a fresh agent per request (statelessness + concurrency, ADR-009 D2), decode the request via the negotiated WireProtocol, merge correlation/tracing headers into config (ADR-009 D4), and populate the agent's typed context from the request. /stream streams the encoded events; /invoke returns the buffered result as JSON.

Classes

BackgroundServer

BackgroundServer(server: uvicorn.Server, thread: threading.Thread)

Handle to a uvicorn server running in a daemon thread.

Holds the thread so shutdown is explicit: :meth:stop flips should_exit and JOINS the thread. A caller draining in-flight turns on SIGTERM must wait for the server to finish — a bare daemon thread cannot guarantee that, since the interpreter can exit while the thread is mid-drain, cutting live turns.

Attribute access delegates to the wrapped uvicorn.Server so existing callers that read .servers/.started or set .should_exit keep working against the handle unchanged.

ServerState

ServerState(secret: str, default_protocol: str = 'ai-sdk', ready: bool = False, draining: bool = False, nonces: NonceStore = InMemoryNonceStore(), max_request_bytes: int = DEFAULT_MAX_REQUEST_BYTES, invoke_timeout_s: float = DEFAULT_INVOKE_TIMEOUT_S, in_flight: int = 0, requests_total: int = 0, status_counts: dict[str, int] = dict(), turns_total: dict[tuple[str, str], int] = dict(), event_answers: IdempotencyCache = IdempotencyCache(), event_timeout_s: float = DEFAULT_EVENT_TIMEOUT_S, turn_attributes: dict[str, MetadataValue] = dict())

Per-process serving state, reachable via app.state.server.

Functions

contract_error

contract_error(status: int, code: str, message: str, details: Any = None) -> JSONResponse

A response in the contract's ContractError shape.

create_app

create_app(make_agent: AgentFactory, secret: str, default_protocol: str = 'ai-sdk', invoke_timeout_s: float = DEFAULT_INVOKE_TIMEOUT_S, nonce_store: NonceStore | None = None, manifest: AgentManifest | None = None, event_timeout_s: float = DEFAULT_EVENT_TIMEOUT_S, turn_attributes: dict[str, MetadataValue] | None = None) -> FastAPI

Build the pod's FastAPI app for the agent make_agent builds.

manifest is served signed at GET /v1/manifest; without one that route answers 404. @event handlers of the agent are served at POST /v1/events/{source}/{name}. turn_attributes (see :func:~latent.serve.knowledge_spans.turn_attributes) go on every turn: on the agent span for /stream, in the response's metadata for /invoke.

inject_context

inject_context(agent: AgentProtocol, config: dict[str, Any]) -> str | None

Populate agent.context from config['context'] per the agent's context_type, and pop it out of the behaviour config.

Mirrors the core of the worker path's context resolution (raw payload → context_type instance → agent.context), minus agent-studio's operator-settability gating and durable-store primitives — those are the studio's, not the served agent's. A conversation_id field is filled from the correlation coordinate when the payload omits it, matching how the worker fills ConversationContext.

The raw payload is rebuilt with a :func:pydantic.TypeAdapter, not context_type(**raw): the wire flattens the context to plain JSON (nested dataclasses become dicts, tuple/set become arrays), so a bare context_type(**raw) would leave a nested field a dict and a tuple field a list. TypeAdapter re-hydrates the declared shape.

Returns an error string (the caller maps it to 422) or None on success.

raw_path

raw_path(request: Request) -> str

The request path exactly as sent, percent-encoding kept, no query.

read_limited_body

read_limited_body(request: Request, limit: int) -> bytes | None

The request body, or None once it exceeds limit bytes.

Counts the bytes as they stream in and stops reading at the limit, so a chunked body with no Content-Length cannot make the process buffer it.

resolve_graceful_timeout

resolve_graceful_timeout(graceful_timeout_s: float | None) -> float

Resolve the graceful-shutdown ceiling, falling back to env then default.

The result is floored at :data:MIN_GRACEFUL_TIMEOUT_S: both consumers int()-truncate it, so a sub-second value would become a zero-second (no) grace window and a negative value an invalid one. A non-finite value (NaN / infinity) would raise deep inside uvicorn's int() at startup, so reject it here with a clear message instead.

resolve_serve_fd

resolve_serve_fd(fd: int | None) -> int | None

Resolve an inherited listening socket descriptor, falling back to env.

fd → uvicorn fd (env LATENT_SERVE_FD). A parent process binds a socket to a reserved port, keeps it open, and passes the descriptor to this child (subprocess pass_fds); uvicorn then serves on it instead of binding host/port itself, which closes the "find free port, close it, spawn" race. None (and an empty env) means "bind host/port normally".

resolve_serve_limits

resolve_serve_limits(max_concurrency: int | None, keep_alive_s: float | None) -> tuple[int | None, float]

Resolve the uvicorn concurrency knobs, falling back to env then defaults.

max_concurrency → uvicorn limit_concurrency (env LATENT_SERVE_MAX_CONCURRENCY): the number of concurrent connections/tasks past which uvicorn sheds load with 503 — which the RemoteAgentProxy maps to unavailable→fallback, so an overloaded pod sheds instead of OOMing. keep_alive_s → uvicorn timeout_keep_alive (env LATENT_SERVE_KEEP_ALIVE). None means "not set here", so env wins.

signed_target

signed_target(request: Request) -> str

The request target Studio signed: scope["raw_path"], then ? and scope["query_string"] when non-empty, bytes as sent.

start_background_server

start_background_server(app: FastAPI, host: str, port: int, log_level: str = 'info', startup_timeout: float = 30.0, max_concurrency: int | None = None, keep_alive_s: float | None = None, fd: int | None = None, graceful_timeout_s: float | None = None) -> BackgroundServer

Run app on a uvicorn server in a daemon thread; return once it's accepting.

The dev-share and deployed supervisors both run the HTTP server alongside an asyncio registration loop on the main thread, so the server lives in a thread. Returns a :class:BackgroundServer handle whose :meth:~BackgroundServer.stop gives an explicit graceful stop + thread join for shutdown draining. Raises rather than spinning forever if the server thread dies before binding (e.g. the port is already in use) or doesn't come up within startup_timeout.

max_concurrency/keep_alive_s tune load-shedding and idle keep-alive; unset, they fall back to LATENT_SERVE_MAX_CONCURRENCY / LATENT_SERVE_KEEP_ALIVE then defaults (see :func:resolve_serve_limits). fd serves on an inherited listening socket instead of binding host:port (env LATENT_SERVE_FD); graceful_timeout_s bounds shutdown draining (env LATENT_SERVE_GRACEFUL_TIMEOUT).

Methods

BackgroundServer.server

BackgroundServer.stop

stop(timeout: float | None = None) -> None

Signal a graceful shutdown and join the server thread.

Sets should_exit (uvicorn stops accepting and drains in-flight turns for up to its timeout_graceful_shutdown), then joins. timeout defaults to the configured graceful window plus a margin; if the thread is still alive past it, force uvicorn to drop remaining connections and join again, so this never blocks the caller forever.

BackgroundServer.thread

ServerState.available

A new turn is admitted only when the pod is registered/ready and not draining. /readyz and the /stream//invoke door share this so a router keying on /readyz and a caller addressing the pod directly see the same verdict.

ServerState.record_status

record_status(code: int) -> None

ServerState.record_turn

record_turn(path: str, outcome: str) -> None

Attributes

AgentFactory

DEFAULT_EVENT_TIMEOUT_S

DEFAULT_GRACEFUL_TIMEOUT_S

DEFAULT_INVOKE_TIMEOUT_S

DEFAULT_KEEP_ALIVE_S

DEFAULT_MAX_REQUEST_BYTES

MIN_GRACEFUL_TIMEOUT_S