Skip to content
Konstera
Docs · Build agents
Konstera documentation.

Getting started, SDK quickstart, manifest reference, kernel MCP services, deploy guide and FAQ — everything you need to build and run agents on Konstera.

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.

ArchitectureThree hooks — where each kind of work belongs Interactive — click a block

The container lifecycle#

Flow1 · Startup — nothing is invoked until /health returns 200 Interactive — click a block
Flow2 · Serving and shutdown Interactive — click a block
StageWhat happens
Container createThe kernel decides to spawn an agent instance, sets KONSTERA_* env vars, mounts the Docker socket (dev-only), and joins the compose network.
Agent process startspython -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 /invokeEnter 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 exitsThe kernel may spawn another when the next invocation arrives.

One invocation, step by step#

SequenceInside a single POST /invoke
KernelSDKYour handle()Kernel services1POST /invoke2enter invocation scopeambient invocationId is set3agent.handle(req, ctx)4ctx.log.* · ctx.llm.*auto-correlated to the invocation5AgentResponse — or raise6HTTP 200 · or 500 + structured error

The three hooks#

initialize(ctx)#

Fires once at startup, after the kernel has injected env vars and before the HTTP server accepts invocations.

Use for
  • 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
Avoid
  • 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.

Guarantees
  • initialize() has completed before this is called
  • The ambient invocationId is 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…MeansKernel sees
Return a business errorThe 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:

Do
  • Use ctx.state for anything that needs to survive container rotation. ctx.state is tenant-persistent.
  • Persist important state via ctx.state.set() inside handle().
  • Re-populate anything cached in initialize() on the next start — it's lost when the container rotates.
Avoid
  • 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.

Python
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:

Python
from konstera_sdk._invocation_context import enter_invocation

async def _background(req_id, ...):
    with enter_invocation(req_id):
        await ctx.log.info("background work", ...)

See also#