Skip to Content
Recodocs

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.

10 min read

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 ownsThe serving layer does not own
Identity, health and capability advertisement for one processThe agent loop and model calls (Agent loop)
Bearer and session checks, origin allow-lists, lease expiryWhich tools a run may call (Tools and permissions)
The typed error envelope (Fault) and per-principal admission limitsRun state, approvals and resume (Harness and state)
Encoding model events as a chat stream, with heartbeats and cleanupAdmission rules, accepted-run outcomes, safe error wording and the Stop button
Signed Slack ingress, a durable channel inbox and outbox, engagement rulesWhat 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 pathTierWhat it is for
recohut_kit.runtimecoreProcess 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.vercelcorestreaming_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.channelscoreNon-HTTP-chat ingress: signed Slack HTTP and Socket Mode, durable ChannelStore, Worker, engagement rules, bounded thread context, image intake, approval buttons.
recohut_kit.service_limitssupportedServiceLimits, 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.servingsupportedFastAPIServing: /health and /ready probes, sse() and error() helpers.
recohut_kit.streamssupportedjson_event and parse_sse: small SSE wire helpers with checked event names and ids.
recohut_kit.ui_streamsupportedHand-written AI SDK UI message-stream parts and UIStreamWriter, for producers that are not PydanticAI.
recohut_kit.ui_specsupportedClosed, data-free UI composition proposals: validate, schema. Standard library only.
recohut_kit.intelligent_uisupportedGenerated-artifact contracts, SQLite history, a FastAPI router, and ArtifactPublisher. Host supplies authentication.
recohut_kit.agents.servingsupportedA FastAPI router for draft edits of an agent catalog. Runtime owns bearer auth.
recohut_kit.integrationssupportedOptional 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 pathWhat it is for
recohut_kit.streamingDependency-free SSE parser, request envelope, bounded replay and connection admission.
recohut_kit.contractsOpt-in Pydantic request, response and settings schemas for HTTP and batch boundaries.
recohut_kit.serving_openapiExport a kit-served app's OpenAPI document with the kit's wire contracts (export_openapi).
recohut_kit.serving_djangoMount one ServiceContract in Django and check parity with the FastAPI rendering.
recohut_kit.agentcoreServe a kit handler on Amazon Bedrock AgentCore, deploy it, and attach Gateway, Memory, Identity, Policy and observability adapters. Spans several layers.
recohut_kit.a2aAgent-to-agent coordination policy: card identities, delegation attribution, directory. Wire semantics come from the official SDK.
recohut_kit.inferenceInference-serving contracts: composite identities, canaries, stage budgets, drift.
recohut_kit.deploymentPrice tables, routing policies, log sampling, monitors and deployment manifests as typed records.
recohut_kit.identityPasswordless and passkey sign-in mechanics.
recohut_kit.notificationsDeep-link parsing, an idempotent notification outbox and a hashed device registry.
recohut_kit.automationPlatform-neutral WorkflowSpec with n8n and Make exporters and a signed webhook round trip.
recohut_kit.local_stackExact-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.

service.py
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)
output
{'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}}
401

In 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.

chat.py
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.

guard.py
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.

limits.py
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:

429 body
{
  "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:

probes.py
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.

writer.py
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.

slack_worker.py
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, deliver

Slack'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 needUseWhy
An HTTP agent endpoint for a browserruntime plus ui.vercel.streaming_responseIdentity and auth from one, the chat stream from the other. Neither pulls the other's dependencies.
Chat stream, but the producer is not PydanticAIui_stream.UIStreamWriterSame wire shape, hand-written, with ordering checks.
Slack mentions, threads and buttonschannelsSigned ingress, a durable inbox and outbox, and recovery after a restart.
Readiness separate from livenessserving.FastAPIServing.install_probesruntime has no readiness hook. Give the two probes different paths.
Rate and concurrency limits per user and tenantservice_limits through install_runtimeKeyed on the verified principal. Use the Redis backend when more than one process serves.
A published OpenAPI documentserving_openapi.export_openapiIncludes the kit's wire contracts next to your routes.
Running on AgentCoreagentcoreA 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 401 with {"detail": {"code": "unauthorized"}}. Pass unauthorized=Fault(...) to render your own envelope instead.
  • Admission also counts capability reads. Under ServiceLimits, GET /v1/capabilities is an authenticated /v1 request and consumes the same window as any other call.
  • streaming_response is 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, and ui_stream provides 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. runtime serves /health; FastAPIServing.install_probes raises ValueError if the health and readiness paths are equal, and will conflict with runtime if you reuse /health.
  • Importing is cheap. recohut_kit.runtime and recohut_kit.channels import no FastAPI, Starlette or Slack SDK until you use the parts that need them.
  • Containment is declared, not enforced. ContainmentDeclaration reports 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 InProcessLimitBackend keeps state in memory. Several workers each get their own counters unless you supply the Redis backend.

How is this page?

Last updated on