Skip to content
Konstera
Docs · Get started
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.

Code examples

Three complete, meaningful agents — Hello World, RAG Q&A, and Refund Approval HITL — broken into labelled sections you can read in order. Each code section has a tab strip so you can switch between Python, TypeScript, and .NET without scrolling or losing your place.

The manifest + Dockerfile sit at the bottom of each agent (they're largely the same across languages, so no need to tab them).

AgentWhat it showsKernel services usedManifest autonomy
1 — Hello WorldVerify your dev environment; runs in direct-run modectx.logautonomous
2 — RAG Q&AGrounded, cited answers over an indexed knowledge basectx.vector, ctx.llm, ctx.logrequire_review
3 — Refund Approval HITLCapability indirection + human approval togetherctx.capability, ctx.human, ctx.state, ctx.logrequire_approval

Agent 1 — Hello World#

The smallest useful agent. Takes a name, logs it, returns a greeting. No kernel calls that would fail in direct-run mode — this is what you use to verify your dev environment.

FlowHello World — one handler, no data-returning kernel calls Interactive — click a block

1.1 — Imports + agent class skeleton#

Python
# main.py
from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run


class HelloAgent(Agent):
    """Minimum useful agent — logs + echoes a greeting."""
    pass  # handle() goes here (next section)

1.2 — The handler#

Pull the name from the request, default to "world", log for observability, return the response.

Python
async def handle(
    self, req: AgentRequest, ctx: AgentContext
) -> AgentResponse:
    # Default to "world" if the request didn't name anyone
    name = req.input.strip() or "world"

    # Fire-and-forget log — kernel ties it to this invocation via ambient scope
    await ctx.log.info(f"Hello, {name}!", echo_of=name)

    # Business output goes in `content`; machine-readable goes in `structured`
    return AgentResponse(content=f"Hello, {name}!")

1.3 — Entry point#

Python
# At the bottom of main.py
if __name__ == "__main__":
    run(HelloAgent())

1.4 — Manifest#

JSON
{
  "$schema": "https://schemas.konstera.ai/agent-manifest.v3.json",
  "id": "io.konstera.hello-world",
  "version": "0.1.0",
  "name": "Hello World",
  "icon": "👋",
  "autonomy": "autonomous",
  "runtime": {
    "kind": "container",
    "image": "ghcr.io/your-org/hello-world:0.1.0",
    "port": 8080,
    "healthPath": "/health"
  },
  "input": {
    "type": "object",
    "properties": { "input": { "type": "string" } }
  },
  "capabilities": { "needs": [] }
}

1.5 — Dockerfile#

Dockerfile
FROM python:3.13-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir konstera-sdk
EXPOSE 8080
ENTRYPOINT ["python", "-u", "main.py"]

Agent 2 — RAG Q&A#

Grounded question-answering over an indexed knowledge base. Retrieves top-K chunks from the vector store, feeds them to the LLM with grounding instructions, returns a cited answer.

Prerequisite: policies already indexed (either via a separate ingestion agent or in this agent's initialize()).

FlowRAG Q&A — retrieve, ground, answer with citations Interactive — click a block

2.1 — Fetch top-K relevant chunks#

Query the vector store with the user's question. Return a visible error if the index is empty — silent "I don't know" is worse than a loud failure.

Python
# Inside RagAgent.handle(), after validating the question:
hits = await ctx.vector.query(
    namespace="shared:policies",   # tenant-wide knowledge base
    query_text=question,
    top_k=5,                       # 5 is enough for most prompts; 500 tokens/hit
)

if not hits:
    # Loud failure — the policy index is empty or the query didn't match
    await ctx.log.warn("rag.no_hits", question=question)
    return AgentResponse(
        content="I couldn't find any relevant policy. Please contact support.",
        structured={"hits": 0},
    )

2.2 — Build a grounded prompt#

Format the retrieved snippets into a numbered list the LLM can cite. The system prompt forbids inventing policy not present in the snippets.

Python
# Build the context block from the top-K hits, including the source
# metadata so the LLM can cite it
context_block = "\n\n".join(
    f"[{i + 1}] (score {h.score:.2f}, {h.metadata.get('source', 'unknown')})"
    f"\n{h.content}"
    for i, h in enumerate(hits)
)

system = (
    "You answer customer questions grounded in the policy snippets provided. "
    "If the snippets don't cover the question, say so — never invent policy. "
    "Cite the snippet number inline, like [1] or [3]."
)
user = f"Policy snippets:\n\n{context_block}\n\nQuestion: {question}"

2.3 — Call the LLM and return#

Use purpose="narrator" so the tenant admin can rebind the model without touching this agent's code. Low temperature for grounded Q&A.

Python
# Kernel routes 'narrator' purpose to the tenant's bound model;
# cost is metered automatically — no need to call ctx.cost.record
result = await ctx.llm.complete(
    prompt=user,
    system=system,
    purpose="narrator",
    temperature=0.1,              # Grounded Q&A wants deterministic output
)

# Observability — hit count, top score, cost
await ctx.log.info(
    "rag.done",
    hits=len(hits),
    top_score=hits[0].score,
    cost_usd=result.cost_usd,
)

return AgentResponse(
    content=result.content,
    structured={
        "hits": len(hits),
        "top_score": hits[0].score,
        "snippets_used": [h.external_id or h.id for h in hits],
    },
)

2.4 — Manifest#

JSON
{
  "$schema": "https://schemas.konstera.ai/agent-manifest.v3.json",
  "id": "io.konstera.rag-policy-qna",
  "version": "0.1.0",
  "name": "Policy Q&A (RAG)",
  "icon": "📚",
  "autonomy": "require_review",
  "runtime": {
    "kind": "container",
    "image": "ghcr.io/your-org/rag-policy-qna:0.1.0",
    "port": 8080,
    "healthPath": "/health",
    "timeoutSeconds": 30,
    "memoryMi": 512
  },
  "input": {
    "type": "object",
    "required": ["question"],
    "properties": { "question": { "type": "string" } }
  },
  "llmRequirements": [
    {
      "purpose": "narrator",
      "suggestedModel": "claude-sonnet-4-6",
      "maxTokens": 1024,
      "description": "Generates a grounded answer from policy snippets."
    }
  ],
  "capabilities": { "needs": [] }
}

For the complete recipe (indexing, extensions, pitfalls) see Cookbook: RAG agent.

Agent 3 — Refund Approval HITL#

Human-in-the-loop refund approval. Fetches order + customer context, drafts a reply, parks on reviewer approval, sends on approve. The pattern that proves out capability indirection + ctx.human.request() together.

SequenceRefund Approval — the agent gathers context, a human decides, the agent acts
Your agentCapabilitiesReviewer inboxState1orders.lookup_by_id2customers.lookup_by_emailorder: required · customer: optional3ctx.human.request() T1, wait 30s4approved · pending · rejected / reworked5if approved: tickets.reply6if pending: store approval ID

3.1 — Validate input + fetch required order#

The order lookup is a required capability — no available() guard needed; the kernel refuses install if the operator hasn't bound it.

Python
async def handle(self, req: AgentRequest, ctx: AgentContext):
    # Payload is a dict (Pydantic-validated against manifest.input)
    payload = req.payload or {}
    order_id = payload.get("order_id")
    ticket_id = payload.get("ticket_id")
    if not order_id or not ticket_id:
        return AgentResponse(
            content="",
            structured={"error": "order_id and ticket_id required"},
        )

    await ctx.log.info("refund.start", order_id=order_id, ticket_id=ticket_id)

    # Required capability — the install guarantees this is bound
    order = await ctx.capability.call("orders.lookup_by_id", id=order_id)
    if not order:
        # Order not found is a business error, not a bug — return it structured
        return AgentResponse(
            content="",
            structured={"error": "order not found"},
        )

3.2 — Optionally enrich with customer tier#

The customer lookup is optional — different tenants bind different vendors, some don't bind this at all. Guard with available().

Python
# Optional capability — guard before calling to avoid CapabilityUnbound
customer = None
if await ctx.capability.available("customers.lookup_by_email"):
    customer = await ctx.capability.call(
        "customers.lookup_by_email", email=order["customer_email"]
    )
# If unbound, customer stays None and the draft falls back to generic phrasing

3.3 — Draft the reply + submit to reviewer inbox#

Submit as T1 (sits pending until a human acts) with waitSeconds=30 for a synchronous resolution if the reviewer is online.

Python
# Draft the reply using whatever context we were able to gather
draft = self._draft_reply(order, customer)

# T1 approval — sits pending; wait up to 30s for a human to act
decision = await ctx.human.request(
    kind="refund-reply",
    tier="T1",
    summary=f"Refund approval for order {order_id} ({order['total_usd']} USD)",
    detail={
        "order_id": order_id,
        "ticket_id": ticket_id,
        "customer_tier": (customer or {}).get("tier", "unknown"),
        "order_total_usd": order["total_usd"],
        "draft_reply": draft,
    },
    options=["approve", "reject", "rework"],
    wait_seconds=30,
)

3.4 — Branch on the decision#

Three outcomes:

DecisionWhat the agent does
approvedSend the reply and return success
pendingStore the approval ID for a later invocation to pick up
rejected / reworkedLog the reason for future training
Python
# Approved — send via the required tickets.reply capability
if decision.is_approved:
    await ctx.capability.call(
        "tickets.reply", ticket_id=ticket_id, body=draft,
    )
    await ctx.log.info("refund.sent", approved_by=decision.approver_actor_id)
    return AgentResponse(
        content=draft,
        structured={"status": "sent", "approval_id": decision.approval_id},
    )

# Pending — reviewer wasn't online within 30s. Persist the approval
# ID so a later invocation can resume via ctx.human.get()
if decision.status == "pending":
    await ctx.state.set(f"pending-refund:{ticket_id}", decision.approval_id)
    return AgentResponse(
        content="",
        structured={"status": "pending", "approval_id": decision.approval_id},
    )

# Rejected or reworked — log the reason; it becomes training data later
await ctx.log.info(
    "refund.rejected",
    reason=decision.decision_reason,
    decision=decision.decision,
)
return AgentResponse(
    content="",
    structured={
        "status": decision.status,
        "reason": decision.decision_reason,
    },
)

3.5 — Manifest#

JSON
{
  "$schema": "https://schemas.konstera.ai/agent-manifest.v3.json",
  "id": "io.konstera.refund-approval",
  "version": "0.1.0",
  "name": "Refund Approval (HITL)",
  "icon": "✅",
  "autonomy": "require_approval",
  "runtime": {
    "kind": "container",
    "image": "ghcr.io/your-org/refund-approval:0.1.0",
    "port": 8080,
    "healthPath": "/health",
    "timeoutSeconds": 60,
    "memoryMi": 384
  },
  "input": {
    "type": "object",
    "required": ["order_id", "ticket_id"],
    "properties": {
      "order_id":  { "type": "string" },
      "ticket_id": { "type": "string" }
    }
  },
  "capabilities": {
    "needs": [
      {
        "name": "orders.lookup_by_id",
        "required": true,
        "reason": "Fetch order details for the approval context"
      },
      {
        "name": "customers.lookup_by_email",
        "required": false,
        "reason": "Enrich with the customer's loyalty tier"
      },
      {
        "name": "tickets.reply",
        "required": true,
        "reason": "Send the approved reply on the originating ticket"
      }
    ]
  }
}

For the complete recipe (reviewer UX, redraft chain pattern, cluster-aware autopilot gating) see Cookbook: Human-in-the-loop.

What stays the same across languages#

  • Manifest — identical. Agents in different languages can reuse the exact same manifest.json.
  • Capability names — canonical strings; same across all tenants and all languages.
  • Service method semantics — same behaviour, same error cases, same direct-run no-op contract.
  • Error types — CapabilityUnbound / CapabilityUpstreamFailed are typed exceptions across all three SDKs.

What differs#

PythonTypeScript.NET
Namingsnake_casecamelCasePascalCase
Method callctx.vector.query(ns, q, top_k=5)ctx.vector.query({ namespace, queryText, topK: 5 })ctx.Vector.QueryAsync(namespace, queryText, topK: 5)
HTTP responseAgentResponse(...) dataclassobject literal { content: ... }anonymous record new { content = ... }
isApproveddecision.is_approved propertyisApproved(decision) helperdecision.IsApproved property
Null-checkif customer:if (customer)customer?.Property

See also#