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).
| Agent | What it shows | Kernel services used | Manifest autonomy |
|---|---|---|---|
| 1 — Hello World | Verify your dev environment; runs in direct-run mode | ctx.log | autonomous |
| 2 — RAG Q&A | Grounded, cited answers over an indexed knowledge base | ctx.vector, ctx.llm, ctx.log | require_review |
| 3 — Refund Approval HITL | Capability indirection + human approval together | ctx.capability, ctx.human, ctx.state, ctx.log | require_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.
1.1 — Imports + agent class skeleton#
# 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)
// main.ts
import { Agent, AgentContext, AgentRequest, AgentResponse, run } from "@konstera/sdk";
/** Minimum useful agent — logs + echoes a greeting. */
class HelloAgent extends Agent {
// handle() goes here (next section)
}
// Program.cs
using Konstera.Sdk;
// Minimum useful agent — logs + echoes a greeting.
var agent = new Agent("io.konstera.hello-world");
// handle registration goes here (next section)
1.2 — The handler#
Pull the name from the request, default to "world", log for observability,
return the response.
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}!")
async handle(req: AgentRequest, ctx: AgentContext): Promise<AgentResponse> {
// Default to "world" if the request didn't name anyone
const name = req.input.trim() || "world";
// Fire-and-forget log — kernel ties it to this invocation via ambient scope
await ctx.log.info(`Hello, ${name}!`, { echo_of: name });
// Business output goes in `content`; machine-readable goes in `structured`
return { content: `Hello, ${name}!` };
}
agent.OnInvoke(async (ctx) =>
{
// Default to "world" if the request didn't name anyone
var name = ctx.Input<string>()?.Trim() ?? "world";
if (string.IsNullOrEmpty(name)) name = "world";
// Fire-and-forget log — kernel ties it to this invocation via ambient scope
await ctx.Log.InfoAsync($"Hello, {name}!", new { echo_of = name });
// Return an anonymous record — the SDK serialises to the response shape
return new { content = $"Hello, {name}!" };
});
1.3 — Entry point#
# At the bottom of main.py
if __name__ == "__main__":
run(HelloAgent())
// At the bottom of main.ts
run(new HelloAgent());
// At the bottom of Program.cs
await agent.RunAsync();
1.4 — Manifest#
{
"$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#
FROM python:3.13-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir konstera-sdk
EXPOSE 8080
ENTRYPOINT ["python", "-u", "main.py"]
FROM node:20-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npx tsc
FROM node:20-slim
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/main.js ./
EXPOSE 8080
ENTRYPOINT ["node", "main.js"]
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app .
EXPOSE 8080
ENTRYPOINT ["dotnet", "HelloAgent.dll"]
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()).
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.
# 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},
)
// Inside RagAgent.handle(), after validating the question:
const hits = await ctx.vector.query({
namespace: "shared:policies", // tenant-wide knowledge base
queryText: question,
topK: 5, // 5 is enough for most prompts; ~500 tokens/hit
});
if (hits.length === 0) {
// Loud failure — the policy index is empty or the query didn't match
await ctx.log.warn("rag.no_hits", { question });
return {
content: "I couldn't find any relevant policy. Please contact support.",
structured: { hits: 0 },
};
}
// Inside the OnInvoke handler, after validating the question:
var hits = await ctx.Vector.QueryAsync(
namespaceName: "shared:policies", // tenant-wide knowledge base
queryText: question,
topK: 5 // ~500 tokens/hit
);
if (hits.Count == 0)
{
// Loud failure — the policy index is empty or the query didn't match
await ctx.Log.WarnAsync("rag.no_hits", new { question });
return new {
content = "I couldn't find any relevant policy. Please contact support.",
structured = new { 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.
# 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}"
// Build the context block from the top-K hits, including the source
// metadata so the LLM can cite it
const contextBlock = hits
.map(
(h, i) =>
`[${i + 1}] (score ${h.score.toFixed(2)}, ${h.metadata["source"] ?? "unknown"})\n${h.content}`,
)
.join("\n\n");
const 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].";
const user = `Policy snippets:\n\n${contextBlock}\n\nQuestion: ${question}`;
// Build the context block from the top-K hits, including the source
// metadata so the LLM can cite it
var contextBlock = string.Join("\n\n", hits.Select((h, i) =>
$"[{i + 1}] (score {h.Score:F2}, {h.Metadata.GetValueOrDefault("source", "unknown")})" +
$"\n{h.Content}"
));
var 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].";
var user = $"Policy snippets:\n\n{contextBlock}\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.
# 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],
},
)
// Kernel routes 'narrator' purpose to the tenant's bound model;
// cost is metered automatically — no need to call ctx.cost.record
const result = await ctx.llm.complete({
prompt: user,
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: hits.length,
top_score: hits[0]!.score,
cost_usd: result.costUsd,
});
return {
content: result.content,
structured: {
hits: hits.length,
top_score: hits[0]!.score,
snippets_used: hits.map((h) => h.externalId ?? h.id),
},
};
// Kernel routes "narrator" purpose to the tenant's bound model;
// cost is metered automatically — no need to call ctx.Cost.RecordAsync
var result = await ctx.Llm.CompleteAsync(new LlmRequest
{
Prompt = user,
System = system,
Purpose = "narrator",
Temperature = 0.1 // Grounded Q&A wants deterministic output
});
// Observability — hit count, top score, cost
await ctx.Log.InfoAsync("rag.done", new {
hits = hits.Count,
top_score = hits[0].Score,
cost_usd = result.CostUsd
});
return new {
content = result.Content,
structured = new {
hits = hits.Count,
top_score = hits[0].Score,
snippets_used = hits.Select(h => h.ExternalId ?? h.Id).ToList()
}
};
2.4 — Manifest#
{
"$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.
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.
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"},
)
async handle(req: AgentRequest, ctx: AgentContext): Promise<AgentResponse> {
// Payload is a dict; destructure the two fields we need
const payload = (req.payload ?? {}) as { order_id?: string; ticket_id?: string };
const { order_id: orderId, ticket_id: ticketId } = payload;
if (!orderId || !ticketId) {
return {
content: "",
structured: { error: "order_id and ticket_id required" },
};
}
await ctx.log.info("refund.start", { order_id: orderId, ticket_id: ticketId });
// Required capability — the install guarantees this is bound
const order = await ctx.capability.call("orders.lookup_by_id", { id: orderId }) as
| { id: string; total_usd: number; customer_email: string }
| null;
if (!order) {
// Order not found is a business error, not a bug — return it structured
return { content: "", structured: { error: "order not found" } };
}
agent.OnInvoke(async (ctx) =>
{
// Payload binds to a typed record; two required fields
var payload = ctx.Payload<RefundPayload>();
if (string.IsNullOrEmpty(payload.OrderId) || string.IsNullOrEmpty(payload.TicketId))
{
return ctx.Error("order_id and ticket_id required");
}
await ctx.Log.InfoAsync("refund.start",
new { order_id = payload.OrderId, ticket_id = payload.TicketId });
// Required capability — the install guarantees this is bound
var order = await ctx.Capability.CallAsync<OrderDetail>(
"orders.lookup_by_id", new { id = payload.OrderId });
if (order == null)
{
// Order not found is a business error, not a bug — return it structured
return ctx.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().
# 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
// Optional capability — guard before calling to avoid CapabilityUnbound
let customer: { tier?: string } | null = null;
if (await ctx.capability.available("customers.lookup_by_email")) {
customer = await ctx.capability.call("customers.lookup_by_email", {
email: order.customer_email,
}) as { tier?: string } | null;
}
// If unbound, customer stays null and the draft falls back to generic phrasing
// Optional capability — guard before calling to avoid CapabilityUnbound
CustomerDetail? customer = null;
if (await ctx.Capability.AvailableAsync("customers.lookup_by_email"))
{
customer = await ctx.Capability.CallAsync<CustomerDetail>(
"customers.lookup_by_email", new { email = order.CustomerEmail });
}
// If unbound, customer stays null 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.
# 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,
)
// Draft the reply using whatever context we were able to gather
const draft = this.draftReply(order, customer);
// T1 approval — sits pending; wait up to 30s for a human to act
const decision = await ctx.human.request({
kind: "refund-reply",
tier: "T1",
summary: `Refund approval for order ${orderId} (${order.total_usd} USD)`,
detail: {
order_id: orderId,
ticket_id: ticketId,
customer_tier: customer?.tier ?? "unknown",
order_total_usd: order.total_usd,
draft_reply: draft,
},
options: ["approve", "reject", "rework"],
waitSeconds: 30,
});
// Draft the reply using whatever context we were able to gather
var draft = DraftReply(order, customer);
// T1 approval — sits pending; wait up to 30s for a human to act
var decision = await ctx.Human.RequestAsync(new HumanRequest
{
Kind = "refund-reply",
Tier = "T1",
Summary = $"Refund approval for order {payload.OrderId} ({order.TotalUsd} USD)",
Detail = new
{
order_id = payload.OrderId,
ticket_id = payload.TicketId,
customer_tier = customer?.Tier ?? "unknown",
order_total_usd = order.TotalUsd,
draft_reply = draft
},
Options = new[] { "approve", "reject", "rework" },
WaitSeconds = 30
});
3.4 — Branch on the decision#
Three outcomes:
| Decision | What the agent does |
|---|---|
approved | Send the reply and return success |
pending | Store the approval ID for a later invocation to pick up |
rejected / reworked | Log the reason for future training |
# 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,
},
)
import { isApproved } from "@konstera/sdk";
// Approved — send via the required tickets.reply capability
if (isApproved(decision)) {
await ctx.capability.call("tickets.reply", { ticket_id: ticketId, body: draft });
await ctx.log.info("refund.sent", { approved_by: decision.approverActorId });
return {
content: draft,
structured: { status: "sent", approval_id: decision.approvalId },
};
}
// 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(`pending-refund:${ticketId}`, decision.approvalId);
return {
content: "",
structured: { status: "pending", approval_id: decision.approvalId },
};
}
// Rejected or reworked — log the reason; it becomes training data later
await ctx.log.info("refund.rejected", {
reason: decision.decisionReason,
decision: decision.decision,
});
return {
content: "",
structured: {
status: decision.status,
reason: decision.decisionReason,
},
};
// Approved — send via the required tickets.reply capability
if (decision.IsApproved)
{
await ctx.Capability.CallAsync("tickets.reply",
new { ticket_id = payload.TicketId, body = draft });
await ctx.Log.InfoAsync("refund.sent",
new { approved_by = decision.ApproverActorId });
return new {
content = draft,
structured = new {
status = "sent",
approval_id = decision.ApprovalId
}
};
}
// Pending — reviewer wasn't online within 30s. Persist the approval
// ID so a later invocation can resume via ctx.Human.GetAsync()
if (decision.Status == "pending")
{
await ctx.State.SetAsync(
$"pending-refund:{payload.TicketId}", decision.ApprovalId);
return new {
content = "",
structured = new {
status = "pending",
approval_id = decision.ApprovalId
}
};
}
// Rejected or reworked — log the reason; it becomes training data later
await ctx.Log.InfoAsync("refund.rejected",
new { reason = decision.DecisionReason, decision = decision.Decision });
return new {
content = "",
structured = new {
status = decision.Status,
reason = decision.DecisionReason
}
};
3.5 — Manifest#
{
"$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/CapabilityUpstreamFailedare typed exceptions across all three SDKs.
What differs#
| Python | TypeScript | .NET | |
|---|---|---|---|
| Naming | snake_case | camelCase | PascalCase |
| Method call | ctx.vector.query(ns, q, top_k=5) | ctx.vector.query({ namespace, queryText, topK: 5 }) | ctx.Vector.QueryAsync(namespace, queryText, topK: 5) |
| HTTP response | AgentResponse(...) dataclass | object literal { content: ... } | anonymous record new { content = ... } |
| isApproved | decision.is_approved property | isApproved(decision) helper | decision.IsApproved property |
| Null-check | if customer: | if (customer) | customer?.Property |
See also#
12 numbered steps from zero to deployed.
Minimum hello-world.
Ask a coding agent to adapt these to your domain.
Full worked recipe — indexing, extensions, pitfalls.
Full worked recipe — reviewer UX, redraft chain, autopilot gating.