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.
| Role | Detail |
|---|---|
| Reads | ctx.capability (customer lookup, order lookup) |
| Writes | ctx.capability (tickets.reply, only after approval) |
| HITL | ctx.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.
Every call to ctx.human.request() ends in one of three outcomes, and the
handler treats each one differently:
| Decision | What the agent does | Returned 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_seconds | Stores the approval ID in ctx.state under pending-refund:{ticket_id} so a later invocation can pick it up | "pending" + approval_id |
| Rejected / reworked | Logs refund.rejected with decision.decision_reason — training data for later | decision.status + reason |
The three files#
- 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.
Pythonfrom 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()) - 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 inneedscarries areasonand is markedrequiredor 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" } ] } } - Package it — DockerfileDockerfile
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 element | Comes from |
|---|---|
| Summary | Top line — "Refund approval for order o-12345 (85.00 USD)" |
| Detail panel | Structured detail dict rendered as a card (order ID, customer tier, draft reply, etc.) |
| Actions | approve / reject / rework (configurable per options) |
| Decision context on reject | Free-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:
| Tier | Behaviour | Use 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#
| Extension | How |
|---|---|
| Cluster-aware auto-approval | Pair 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 chain | On 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 handling | For 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#
- Use
wait_secondsonly for synchronous flows. For background work usewait_seconds=None(default) and check back viactx.human.get()in a later invocation. - Keep
detailto what the reviewer needs. Thedetaildict is visible in the inbox and the audit log. - Match
requiredto reality.tickets.replyis markedrequired: truebecause the agent can't deliver without it. If you want the agent to still run (and record "no-op" invocations) whentickets.replyisn't bound, mark it optional and guard withavailable().
- 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.
- The risky write (
tickets.reply) happens only on the approved branch. - The
detaildict gives the reviewer full context — and contains no API keys or unnecessary PII. - The pending branch persists the
approval_id(here inctx.state), and something picks it up later (ctx.human.get()or alist_pendingescalation agent). - Rejection and rework reasons are logged from
decision.decision_reason. - Optional capabilities are guarded with
ctx.capability.available();requiredflags in the manifest match what the agent truly can't run without. - The tier is T1 unless eval data justifies T2/T3, and
autonomyin the manifest reflects who must sign off.