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

Cookbook: Human-in-the-loop agent

A complete working recipe. The agent drafts a customer-visible action (a refund approval message), parks on reviewer approval with a clear rationale, and only sends on approve. On reject, it logs the reason for future training.

What you'll have at the end
A refund-approval agent that drafts the customer reply, parks it in the reviewer inbox with full context, sends it on the originating ticket only after approval, and records why anything was rejected.
You need
orders.lookup_by_id capability (required)tickets.reply capability (required)customers.lookup_by_email (optional)konstera-sdk==0.6.0
RoleDetail
Readsctx.capability (customer lookup, order lookup)
Writesctx.capability (tickets.reply, only after approval)
HITLctx.human.request() with tier T1 (sits pending until a human acts) and wait_seconds=30 for synchronous resolution when the reviewer is online

How the agent works#

The agent never executes the risky action on its own judgement. It gathers context, drafts, parks, and only the reviewer's decision unlocks the write.

SequenceDraft → park → reviewer → execute
AgentCapabilitiesctx.humanReviewer1orders.lookup_by_id2order (+ customer tier)3draft the reply4request(tier="T1", wait_seconds=30)5row in reviewer inbox6approve / reject / rework7decision8tickets.reply — only if approved

Every call to ctx.human.request() ends in one of three outcomes, and the handler treats each one differently:

DecisionWhat the agent doesReturned status
Approved (decision.is_approved)Calls tickets.reply with the draft; logs refund.sent with approved_by"sent" + approval_id
Pending — reviewer wasn't online within wait_secondsStores the approval ID in ctx.state under pending-refund:{ticket_id} so a later invocation can pick it up"pending" + approval_id
Rejected / reworkedLogs refund.rejected with decision.decision_reason — training data for laterdecision.status + reason

The three files#

  1. Write the handler — main.py

    Validate the payload, fetch order and (optionally) customer context, draft the reply, park on approval, then branch on the decision.

    Python
    from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run
    
    
    class RefundApprovalAgent(Agent):
        """Drafts refund approval replies; parks on reviewer approval."""
    
        async def handle(
            self, req: AgentRequest, ctx: AgentContext
        ) -> AgentResponse:
            order_id = req.payload.get("order_id") if req.payload else None
            ticket_id = req.payload.get("ticket_id") if req.payload else None
    
            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)
    
            # 1. Fetch order + customer context
            order = await ctx.capability.call("orders.lookup_by_id", id=order_id)
            if not order:
                await ctx.log.warn("refund.order_not_found", order_id=order_id)
                return AgentResponse(
                    content="",
                    structured={"error": "order not found"},
                )
    
            customer = None
            if await ctx.capability.available("customers.lookup_by_email"):
                customer = await ctx.capability.call(
                    "customers.lookup_by_email", email=order["customer_email"]
                )
    
            # 2. Draft the reply
            draft = self._draft_reply(order, customer)
    
            # 3. Park on reviewer approval (T1 = sits pending until human acts)
            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_email": order["customer_email"],
                    "customer_tier": customer.get("tier") if customer else "unknown",
                    "order_total_usd": order["total_usd"],
                    "order_date": order["created_at"],
                    "draft_reply": draft,
                },
                options=["approve", "reject", "rework"],
                wait_seconds=30,
            )
    
            # 4. On approve → send. On reject/pending → store for later.
            if decision.is_approved:
                if await ctx.capability.available("tickets.reply"):
                    await ctx.capability.call(
                        "tickets.reply", ticket_id=ticket_id, body=draft,
                    )
                    await ctx.log.info(
                        "refund.sent",
                        order_id=order_id,
                        approved_by=decision.approver_actor_id,
                    )
                    return AgentResponse(
                        content=draft,
                        structured={"status": "sent", "approval_id": decision.approval_id},
                    )
    
            if decision.status == "pending":
                # Reviewer wasn't online within wait_seconds; store the approval
                # ID in state so a later invocation can pick it up.
                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 reason for future training data
            await ctx.log.info(
                "refund.rejected",
                order_id=order_id,
                reason=decision.decision_reason,
                decision=decision.decision,
            )
            return AgentResponse(
                content="",
                structured={
                    "status": decision.status,
                    "reason": decision.decision_reason,
                },
            )
    
        def _draft_reply(self, order, customer) -> str:
            tier = (customer or {}).get("tier", "")
            tier_note = (
                " As a valued member of our Gold tier, we've prioritised this." if tier == "gold" else ""
            )
            return (
                f"Hello,\n\n"
                f"I've approved a full refund of ${order['total_usd']:.2f} "
                f"for order {order['id']}.{tier_note} "
                f"You'll see the funds back on your card within 5–7 business days.\n\n"
                f"Thanks for your patience,\n"
                f"Customer Success"
            )
    
    
    if __name__ == "__main__":
        run(RefundApprovalAgent())
    
  2. Declare the contract — manifest.json

    "autonomy": "require_approval" is the stronger setting: approval must come from a named reviewer role, configurable per binding (see Manifest reference). Each capability in needs carries a reason and is marked required or optional.

    JSON
    {
      "$schema": "https://schemas.konstera.ai/agent-manifest.v3.json",
      "id": "io.konstera.refund-approval",
      "version": "0.1.0",
      "name": "Refund Approval (HITL)",
      "description": "Drafts refund approval replies; parks on reviewer approval.",
      "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,
        "cpuMillis": 400
      },
      "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 to build the approval context"
          },
          {
            "name": "customers.lookup_by_email",
            "required": false,
            "reason": "Enriches the reviewer's context with the customer's loyalty tier"
          },
          {
            "name": "tickets.reply",
            "required": true,
            "reason": "Send the approved reply back on the originating ticket"
          }
        ]
      }
    }
    
  3. Package it — Dockerfile
    Dockerfile
    FROM python:3.13-slim
    WORKDIR /app
    COPY . .
    RUN pip install --no-cache-dir konstera-sdk==0.6.0
    EXPOSE 8080
    HEALTHCHECK --interval=10s --timeout=3s --start-period=5s \
      CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health', timeout=2)"
    ENTRYPOINT ["python", "-u", "main.py"]
    

How the reviewer experience works#

When the agent calls ctx.human.request(), the reviewer sees a row in the Konstera portal's reviewer inbox with:

Inbox elementComes from
SummaryTop line — "Refund approval for order o-12345 (85.00 USD)"
Detail panelStructured detail dict rendered as a card (order ID, customer tier, draft reply, etc.)
Actionsapprove / reject / rework (configurable per options)
Decision context on rejectFree-text reason captured and returned on decision.decision_reason

For high-volume tiers (T2 auto-stage, T3 straight-through), the kernel resolves the approval synchronously — the agent doesn't block waiting on a human. Pattern:

FlowApproval tiers — from never allowed to fully trusted Interactive — click a block
TierBehaviourUse it for
T0 (blocked)Kernel refuses at submission."This should never happen" guards.
T1 (pending)Sits in the inbox.Default for anything a human really needs to see.
T2 (auto-stage)Auto-approved, but logged for retrospective review.When a rule says the action is safe but you want the audit trail.
T3 (straight-through)Auto-approved on a mature whitelisted rule.Once you have confidence from eval data (e.g. cluster pass rate >= 0.95).

Common extensions#

ExtensionHow
Cluster-aware auto-approvalPair with ctx.semantic.cluster_pass_rate() (ADR-037). Autopilot refunds in clusters with a recent 0.95+ pass rate; everything else goes to T1 review.
Redraft chainOn reviewer "rework" decision, generate a new draft with the reviewer's feedback and submit a new human.request() with parent_approval_id=decision.approval_id to link the chain.
Timeout handlingFor off-hours, run a separate agent that picks up pending approvals via ctx.human.list_pending(mine_only=True) and escalates by email after 24h.

Pitfalls#

Do
  • Use wait_seconds only for synchronous flows. For background work use wait_seconds=None (default) and check back via ctx.human.get() in a later invocation.
  • Keep detail to what the reviewer needs. The detail dict is visible in the inbox and the audit log.
  • Match required to reality. tickets.reply is marked required: true because the agent can't deliver without it. If you want the agent to still run (and record "no-op" invocations) when tickets.reply isn't bound, mark it optional and guard with available().
Avoid
  • Over-rely on wait_seconds: it parks the agent thread for 1–60s — wasteful for background polling.
  • Put secrets in detail: no API keys or customer PII beyond what the reviewer needs.
Before you ship
  • The risky write (tickets.reply) happens only on the approved branch.
  • The detail dict gives the reviewer full context — and contains no API keys or unnecessary PII.
  • The pending branch persists the approval_id (here in ctx.state), and something picks it up later (ctx.human.get() or a list_pending escalation agent).
  • Rejection and rework reasons are logged from decision.decision_reason.
  • Optional capabilities are guarded with ctx.capability.available(); required flags in the manifest match what the agent truly can't run without.
  • The tier is T1 unless eval data justifies T2/T3, and autonomy in the manifest reflects who must sign off.

See also#