Agent lifecycle
What happens from the moment the kernel decides to invoke your agent, through
handle(), to graceful shutdown. Understanding this helps you place work
correctly — initialize() for warm-up, handle() for per-invocation
business logic, shutdown() for cleanup.
The container lifecycle#
KONSTERA_* env varsOpen page run() picks up envinitialize(ctx)one-off setup (default: no-op)Go to step 4HTTP server on :8080/health 200 — kernel marks readyOpen page | Stage | What happens |
|---|---|
| Container create | The kernel decides to spawn an agent instance, sets KONSTERA_* env vars, mounts the Docker socket (dev-only), and joins the compose network. |
| Agent process starts | python -u main.py / dotnet HelloAgent.dll. The SDK's run() picks up the env. |
initialize(ctx) | One-off setup: load models, warm caches, open DB pools, index vectors. Default: no-op. |
| HTTP server begins listening on :8080 | /health returns 200 — the kernel marks the instance ready. |
For each POST /invoke | Enter invocation scope (the SDK sets the ambient invocationId) → agent.handle(req, ctx) runs your business logic → serialize the response (HTTP 200, or 500 with a structured error) → exit invocation scope. |
shutdown(ctx) (on SIGTERM / SIGINT) | Close pools, flush buffers, release locks. Default: no-op. Exceptions here are swallowed so they don't block container exit. |
| Container exits | The kernel may spawn another when the next invocation arrives. |
One invocation, step by step#
The three hooks#
initialize(ctx)#
Fires once at startup, after the kernel has injected env vars and before the HTTP server accepts invocations.
- Loading models or weight files into memory (one-time cost)
- Warming caches you'll read from on every invocation
- Indexing documents into
ctx.vector(if the content is static per deploy) - Opening long-lived DB connection pools
- Fetching tenant config via
ctx.state.get()and caching it
- Making external API calls that could time out — container will fail to come up
- Loading per-invocation data (that belongs in
handle()) - Reading
req— it doesn't exist yet
handle(req, ctx)#
Fires per invocation. The invocation ID is active in the ambient scope
during this call, so ctx.log.* and ctx.llm.* auto-correlate.
initialize()has completed before this is called- The ambient
invocationIdis set —ctx.log.info()picks it up - Exceptions produce HTTP 500 with
{"error": {"type", "message"}}and are logged kernel-side as a failed invocation - A clean
return AgentResponse(...)produces HTTP 200 with the serialised response
Returning vs raising:
Business errors go in the response — for example
return AgentResponse(content="", structured={"error": "customer_not_found"}).
| You… | Means | Kernel sees |
|---|---|---|
| Return a business error | The agent decides what the operational caller does with the structured error. | HTTP 200 |
| Raise an exception | "The invocation itself failed" — treat as bugs. | HTTP 500, logged as a failed invocation |
shutdown(ctx)#
Fires once on SIGTERM or SIGINT, before the HTTP server stops.
Use for:
- Closing DB pools or external connections
- Flushing pending log buffers
- Releasing distributed locks held by the instance
Container reuse (not guaranteed, don't rely on it)#
The kernel may keep a container warm between invocations for latency. It may also spawn one container per invocation (early releases, debug mode). Design assuming either:
- Use
ctx.statefor anything that needs to survive container rotation.ctx.stateis tenant-persistent. - Persist important state via
ctx.state.set()insidehandle(). - Re-populate anything cached in
initialize()on the next start — it's lost when the container rotates.
- Keep in-memory state across invocations that isn't persisted.
- Rely on
shutdown()to persist important state.
Ambient invocation scope#
Inside handle(), the SDK sets an ambient scope with the current
req.invocation_id. Services that need correlation (ctx.log.*,
ctx.capability.call(), ctx.llm.complete()) read it automatically — you
don't thread the ID through your function calls.
async def handle(self, req: AgentRequest, ctx: AgentContext) -> AgentResponse:
# No explicit invocation_id here — SDK fills it in from the ambient scope.
await ctx.log.info("processing", input=req.input)
# Same — the kernel associates this LLM call with req.invocation_id.
result = await ctx.llm.complete(prompt=req.input, purpose="narrator")
return AgentResponse(content=result.content)
If you spawn a background task (asyncio.create_task) and want the
correlation to carry across, use enter_invocation() explicitly:
from konstera_sdk._invocation_context import enter_invocation
async def _background(req_id, ...):
with enter_invocation(req_id):
await ctx.log.info("background work", ...)