Serving
How a kit agent is exposed over HTTP, Slack and streaming chat: the runtime contract, the streaming encoder, channel ingress and the supported and catalog packages around them.
The serving layer is the front door, not the worker behind it. A browser or chat workspace can call it, identify the service, authenticate, discover available operations, follow streamed answers and receive consistently shaped errors. Decisions about the work itself belong in the model loop, tool, approval and state layers behind that door.
The kit splits serving into three seams that fit together: the process contract (recohut_kit.runtime), the model-to-wire stream (recohut_kit_pydantic_ai.ui.vercel) and non-web ingress (recohut_kit.channels). Everything else in the layer is a supported helper or a catalog package you pick up for a specific need.
Where the layer starts and stops
| The serving layer owns | The serving layer does not own |
|---|---|
| Identity, health and capability advertisement for one process | The agent loop and model calls (Agent loop) |
| Bearer and session checks, origin allow-lists, lease expiry | Which tools a run may call (Tools and permissions) |
The typed error envelope (Fault) and per-principal admission limits | Run state, approvals and resume (Harness and state) |
| Encoding model events as a chat stream, with heartbeats and cleanup | Admission rules, accepted-run outcomes, safe error wording and the Stop button |
| Signed Slack ingress, a durable channel inbox and outbox, engagement rules | What the agent says in a thread, and who is allowed to act |
Routes, reviewer authentication and the content of every answer stay in your application. The kit gives you the parts that are the same in every service.
How the pieces fit
The runtime wraps a FastAPI app. The streaming encoder wraps the agent's native event stream. The channel worker wraps the same agent for a different transport and keeps its own SQLite store for thread bindings, receipts and outbound posts.
Owners
Tiers come from the kit's golden-path tier file. Core means the kit recommends it as the default; supported means it has a real consumer; catalog means it is kept and documented but is not the default path.
Core and supported
| Import path | Tier | What it is for |
|---|---|---|
recohut_kit.runtime | core | Process contract: RuntimeIdentity, public /health, bearer-guarded /v1/capabilities, Fault, install_runtime, CapabilityModule, GuardPolicy, SessionGuard. Imports no web framework at import time. |
recohut_kit_pydantic_ai.ui.vercel | core | streaming_response: encodes a PydanticAI event stream as an AI SDK v6 chat stream, with idle heartbeats and same-task cleanup. Ships in the recohut-kit-pydantic-ai distribution. |
recohut_kit.channels | core | Non-HTTP-chat ingress: signed Slack HTTP and Socket Mode, durable ChannelStore, Worker, engagement rules, bounded thread context, image intake, approval buttons. |
recohut_kit.service_limits | supported | ServiceLimits, LimitPolicy and in-process admission by principal, tenant and session. Wired through install_runtime(service_limits=...). A Redis backend is in recohut_kit.service_limits_redis. |
recohut_kit.serving | supported | FastAPIServing: /health and /ready probes, sse() and error() helpers. |
recohut_kit.streams | supported | json_event and parse_sse: small SSE wire helpers with checked event names and ids. |
recohut_kit.ui_stream | supported | Hand-written AI SDK UI message-stream parts and UIStreamWriter, for producers that are not PydanticAI. |
recohut_kit.ui_spec | supported | Closed, data-free UI composition proposals: validate, schema. Standard library only. |
recohut_kit.intelligent_ui | supported | Generated-artifact contracts, SQLite history, a FastAPI router, and ArtifactPublisher. Host supplies authentication. |
recohut_kit.agents.serving | supported | A FastAPI router for draft edits of an agent catalog. Runtime owns bearer auth. |
recohut_kit.integrations | supported | Optional framework and service bindings, each imported explicitly. Serving-related subtrees include streaming_services, async_services, auth_services, fastapi_contracts, a2a_services and langchain_serving. |
Catalog
| Import path | What it is for |
|---|---|
recohut_kit.streaming | Dependency-free SSE parser, request envelope, bounded replay and connection admission. |
recohut_kit.contracts | Opt-in Pydantic request, response and settings schemas for HTTP and batch boundaries. |
recohut_kit.serving_openapi | Export a kit-served app's OpenAPI document with the kit's wire contracts (export_openapi). |
recohut_kit.serving_django | Mount one ServiceContract in Django and check parity with the FastAPI rendering. |
recohut_kit.agentcore | Serve a kit handler on Amazon Bedrock AgentCore, deploy it, and attach Gateway, Memory, Identity, Policy and observability adapters. Spans several layers. |
recohut_kit.a2a | Agent-to-agent coordination policy: card identities, delegation attribution, directory. Wire semantics come from the official SDK. |
recohut_kit.inference | Inference-serving contracts: composite identities, canaries, stage budgets, drift. |
recohut_kit.deployment | Price tables, routing policies, log sampling, monitors and deployment manifests as typed records. |
recohut_kit.identity | Passwordless and passkey sign-in mechanics. |
recohut_kit.notifications | Deep-link parsing, an idempotent notification outbox and a hashed device registry. |
recohut_kit.automation | Platform-neutral WorkflowSpec with n8n and Make exporters and a signed webhook round trip. |
recohut_kit.local_stack | Exact-identity ownership of a throwaway multi-container Docker stack. |
Worked examples
A service with identity, bearer auth and a typed fault
install_runtime wires the Fault handler, a public health route, a bearer-guarded GET /v1/capabilities, and mounts each CapabilityModule router under /v1.
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
from recohut_kit.runtime import CapabilityModule, Fault, RuntimeIdentity, install_runtime
records = APIRouter()
@records.get("/records/{record_id}")
def get_record(record_id: str) -> dict[str, str]:
if record_id != "r1":
raise Fault("not_found", "No such record.", 404)
return {"id": record_id}
identity = RuntimeIdentity(session_id="s-1", runtime_generation="1", session_token="t-1")
app = FastAPI()
install_runtime(app, identity, [CapabilityModule("records", records)])
with TestClient(app) as client:
bearer = {"Authorization": "Bearer t-1"}
print(client.get("/health").json())
print(client.get("/v1/capabilities", headers=bearer).json())
print(client.get("/v1/records/r9", headers=bearer).json())
print(client.get("/v1/records/r1").status_code){'status': 'ok', 'runtime': 'local', 'session_id': 's-1', 'runtime_generation': '1'}
{'api_version': 'v1', 'session_id': 's-1', 'capabilities': ['records']}
{'error': {'code': 'not_found', 'message': 'No such record.', 'retryable': False}}
401In a real deployment the supervisor injects the values as environment variables and you build the identity with RuntimeIdentity.from_prefix("MY_SERVICE") (it reads MY_SERVICE_SESSION_ID, MY_SERVICE_SESSION_TOKEN and the other prefixed names). install_runtime returns an InstalledRuntime; .unwrap() gives back the FastAPI app and .authorize guards routes you add outside /v1.
Streaming a chat answer
The agent chat route is one more CapabilityModule. The route owns the PydanticAI Agent; streaming_response turns its native events into the chat stream.
from fastapi import APIRouter, FastAPI
from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel
from pydantic_ai.ui.vercel_ai import VercelAIEventStream
from pydantic_ai.ui.vercel_ai.request_types import SubmitMessage
from recohut_kit.runtime import CapabilityModule, Fault, RuntimeIdentity, install_runtime
from recohut_kit_pydantic_ai.ui.vercel import streaming_response
agent = Agent(TestModel())
chat = APIRouter()
@chat.post("/chat")
async def post_chat(body: dict):
if not body.get("text"):
raise Fault("empty_message", "Send some text.", 422)
async def native():
async with agent.run_stream_events(body["text"]) as events:
async for event in events:
yield event
encoder = VercelAIEventStream(SubmitMessage(id="m1", messages=[]), sdk_version=6)
return streaming_response(encoder.transform_stream(native()), message_id="m1")
app = FastAPI()
identity = RuntimeIdentity(session_id="s-1", session_token="t-1")
install_runtime(app, identity, [CapabilityModule("chat", chat)])A bearer-authenticated POST /v1/chat returns text/event-stream with Cache-Control: no-cache, X-Accel-Buffering: no and a : heartbeat comment after every heartbeat_seconds (default 5) of idle time. Replace TestModel() with a real model from the Model route layer.
Origin allow-list, lease expiry and a second credential check
GuardPolicy adds a SessionGuard middleware in front of every path except the health route, the docs routes and the public paths you list.
from recohut_kit.runtime import GuardPolicy, RuntimeIdentity, install_runtime
policy = GuardPolicy(
origins=["http://localhost:5173"], # other Origin headers get 403 "denied"
expires_at=lambda: 4102444800.0, # epoch seconds; past this, 410 "expired"
verify=lambda credential: credential == "alt-ok", # optional second acceptor
)
install_runtime(app, identity, [], guard=policy)Per-principal admission limits
ServiceLimits admits each authenticated request against a rate window, a concurrency lease and a session budget. It needs a principal_verifier so the limits key on a server-verified identity, never on a field in the request body.
from recohut_kit.learning.access import Principal
from recohut_kit.runtime import RuntimeIdentity, install_runtime
from recohut_kit.service_limits import LimitPolicy, ServiceLimits
install_runtime(
app,
RuntimeIdentity(session_id="s1"),
[],
principal_verifier=lambda token: Principal("u1", "t1", "test") if token == "tok" else None,
service_limits=ServiceLimits(policy=LimitPolicy(principal_requests=2)),
)With principal_requests=2, the third request in a window returns 429 with the standard envelope:
{
"error": {
"code": "rate_limited",
"message": "Service admission limit reached.",
"retryable": true,
"details": { "limit": "principal_rate", "retry_after_seconds": 15.5 }
}
}The response also carries a Retry-After header in whole seconds.
Readiness probes and manual SSE
runtime serves /health but has no readiness hook. FastAPIServing adds one, on paths you choose so they do not collide:
from fastapi import FastAPI
from recohut_kit.serving import FastAPIServing
from recohut_kit.streams import json_event, parse_sse
app = FastAPI()
serving = FastAPIServing(app)
async def ready() -> bool:
return False # check your own dependencies here
serving.install_probes(ready=ready, health_path="/live", readiness_path="/ready")
# GET /live -> 200 {"status": "ok"}; GET /ready -> 503 {"status": "unavailable"}
frame = json_event({"n": 1}, event="tick", identifier=7)
# 'id: 7\nevent: tick\ndata: {"n":1}\n\n'
print(list(parse_sse(frame)))Hand-written chat stream parts
When the producer is not PydanticAI, UIStreamWriter checks order and shape before it encodes each part, so a malformed stream fails in your code and not in the browser.
from recohut_kit import ui_stream
writer = ui_stream.UIStreamWriter()
frames = [
writer.write(ui_stream.start("m1")),
writer.write(ui_stream.text_start("t1")),
writer.write(ui_stream.text_delta("t1", "Hello")),
writer.write(ui_stream.text_end("t1")),
writer.write(ui_stream.finish()),
writer.done(),
]
# Each item is 'data: {...}\n\n'; done() returns 'data: [DONE]\n\n'.
# Any further write raises ui_stream.UIStreamError("The stream is closed").A Slack channel with durable acceptance
channels.worker.Worker accepts an event once, stores a binding, then runs your Application hooks and posts through your Delivery. Retried events do not run twice.
import asyncio
from pathlib import Path
from recohut_kit.channels.contracts import Binding, Incoming, Outcome, Principal, Thread
from recohut_kit.channels.sqlite import ChannelStore
from recohut_kit.channels.worker import Worker
class App:
def authorize(self, incoming: Incoming, binding: Binding | None) -> Principal:
if incoming.user != "mapped":
raise PermissionError("No authority")
return Principal("operator", frozenset({"conversation.submit"}))
async def execute(self, incoming, binding, actor, submission) -> Outcome:
return Outcome("completed", binding.conversation, submission, {"answer": "Accepted"})
async def reconcile(self, incoming, binding, actor, submission) -> Outcome:
return Outcome("completed", binding.conversation, submission, {"answer": "Read back"})
class Delivery:
async def send(self, incoming, outcome, identity, message=None) -> str:
return message or "1730000001.000002"
event = Incoming(
"event-1",
Thread("app", "team", "channel", "1730000000.000001"),
"mapped",
"1730000000.000001",
"mention",
"Find offers",
)
worker = Worker(ChannelStore(Path("channel.sqlite")), App(), Delivery(), lambda *a: None)
first = worker.accept(event)
assert worker.accept(event) == first # a retried mention has one binding
asyncio.run(worker.step()) # authorize, execute, deliverSlack's own SDK is optional (recohut-kit[slack]); importing recohut_kit.channels loads none of it. channels.engagement.EngagementRules and decide add the reply rules: requester-only replies, ignoring other mentions, and going silent after a human takes over the thread.
Choosing between owners
| You need | Use | Why |
|---|---|---|
| An HTTP agent endpoint for a browser | runtime plus ui.vercel.streaming_response | Identity and auth from one, the chat stream from the other. Neither pulls the other's dependencies. |
| Chat stream, but the producer is not PydanticAI | ui_stream.UIStreamWriter | Same wire shape, hand-written, with ordering checks. |
| Slack mentions, threads and buttons | channels | Signed ingress, a durable inbox and outbox, and recovery after a restart. |
| Readiness separate from liveness | serving.FastAPIServing.install_probes | runtime has no readiness hook. Give the two probes different paths. |
| Rate and concurrency limits per user and tenant | service_limits through install_runtime | Keyed on the verified principal. Use the Redis backend when more than one process serves. |
| A published OpenAPI document | serving_openapi.export_openapi | Includes the kit's wire contracts next to your routes. |
| Running on AgentCore | agentcore | A deployment target, not the default serving path. |
Failure behaviour, limits and gotchas
- Missing token fails closed. With no configured token and no verifier, protected routes return 503 rather than opening. Opening them takes an explicit
allow_unauthenticated_access=True, which logs a warning and advertises the open mode in/v1/capabilities. - Two bearer rejections look different. A plain rejection is
401with{"detail": {"code": "unauthorized"}}. Passunauthorized=Fault(...)to render your own envelope instead. - Admission also counts capability reads. Under
ServiceLimits,GET /v1/capabilitiesis an authenticated/v1request and consumes the same window as any other call. streaming_responseis only the encoder. You own admission, whether a run was accepted, safe error text and any Stop control. The adapter has no abort or tool-approval frames, andui_streamprovides none either, so approval prompts in the chat stream are application work.- A heartbeat never cancels work. The idle comment is emitted while the producer read stays pending. If the client disconnects, the producer is closed in the same task that iterated it.
- Two health routes cannot share a path.
runtimeserves/health;FastAPIServing.install_probesraisesValueErrorif the health and readiness paths are equal, and will conflict withruntimeif you reuse/health. - Importing is cheap.
recohut_kit.runtimeandrecohut_kit.channelsimport no FastAPI, Starlette or Slack SDK until you use the parts that need them. - Containment is declared, not enforced.
ContainmentDeclarationreports what the host says about egress and filesystem roots. The capabilities payload labels it "declared, not verified". - In-process limits are per process. The default
InProcessLimitBackendkeeps state in memory. Several workers each get their own counters unless you supply the Redis backend.
How is this page?
Last updated on