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: Eval-driven agent development

Treat eval scenarios like unit tests, declared in the manifest. The platform runs them on upload + nightly + on-demand. CI fails on regressions; autopilot gates on recent cluster pass rates.

Reads: scenario inputs (from manifest or Context Service). Writes: eval run results into tenant_context_evaluation_run. Autopilot: ctx.semantic.cluster_pass_rate(cluster_tag) gates auto-approval on recent eval quality.

The eval block#

Declared in the manifest (v3.1 adds this):

JSON
{
  "$schema": "https://schemas.konstera.ai/agent-manifest.v3.json",
  "id": "io.konstera.refund-handler",
  "version": "0.2.0",
  "runtime": { "kind": "container", "image": "..." },
  "autonomy": "autonomous",
  "input": { "type": "object" },
  "eval": {
    "endpoint": "/eval",
    "timeout_seconds": 60,
    "scenarios": [
      {
        "id": "refund-eligible-vip-gold",
        "cluster_tag": "refund-eligible",
        "input": {
          "order_id": "o-123",
          "customer_tier": "gold",
          "days_since_delivery": 15
        },
        "expected": {
          "decision": "approve",
          "confidence_gte": 0.8
        }
      },
      {
        "id": "refund-outside-window",
        "cluster_tag": "refund-ineligible-window",
        "input": {
          "order_id": "o-124",
          "customer_tier": "silver",
          "days_since_delivery": 45
        },
        "expected": {
          "decision": "reject",
          "reason_contains": "window"
        }
      }
    ]
  }
}

Each scenario has an id, optional cluster_tag (for grouping similar scenarios in reports + autopilot gates), input (passed to the agent's /eval endpoint), and expected (what the harness checks).

Implementing /eval#

Beyond the normal /invoke, the agent exposes /eval that runs the scenario deterministically — fixtures instead of real capability calls:

Python
from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run


class RefundHandlerAgent(Agent):
    """Decides refund eligibility."""

    async def handle(self, req, ctx):
        payload = req.payload or {}
        order_id = payload.get("order_id")
        # Normal path: fetch order from capability
        order = await ctx.capability.call("orders.lookup_by_id", id=order_id)
        return await self._decide(order, ctx)

    async def eval(self, req, ctx):
        """Deterministic eval path — uses fixtures instead of capabilities."""
        payload = req.payload or {}
        # Fabricate an order from the scenario input (no capability call)
        order = {
            "id": payload["order_id"],
            "customer_tier": payload["customer_tier"],
            "days_since_delivery": payload["days_since_delivery"],
        }
        return await self._decide(order, ctx)

    async def _decide(self, order, ctx):
        """The actual decision logic — shared between /invoke and /eval."""
        if order["days_since_delivery"] > 30:
            return AgentResponse(
                content="",
                structured={"decision": "reject", "reason": "outside 30-day window", "confidence": 1.0},
            )
        tier_bonus = {"gold": 0.1, "silver": 0.05, "bronze": 0.0}.get(order["customer_tier"], 0.0)
        confidence = min(1.0, 0.75 + tier_bonus)
        return AgentResponse(
            content="",
            structured={"decision": "approve", "confidence": confidence},
        )


if __name__ == "__main__":
    run(RefundHandlerAgent())

The SDK's run() auto-wires /eval if the agent class has an eval() method with the same signature as handle().

How the harness runs scenarios#

On upload (and nightly, and when triggered manually):

  1. Platform POSTs each scenario's input to /eval as req.payload
  2. Agent returns an AgentResponse with structured
  3. Platform compares structured against expected:
    • decision == "approve" ✅
    • confidence >= 0.8 ✅
    • reason_contains "window" → checks substring ✅
  4. Each pass/fail recorded in tenant_context_evaluation_run with the cluster tag + scenario ID + full response for debugging

Gating autopilot on cluster pass rate#

Once you have reliable eval results, use them to gate real-world autonomous actions:

Python
async def handle(self, req, ctx):
    order_id = req.payload["order_id"]
    order = await ctx.capability.call("orders.lookup_by_id", id=order_id)

    # Classify what cluster this request belongs to
    cluster = self._classify_cluster(order)  # e.g. "refund-eligible"

    # Fetch recent pass rate for THIS agent on THIS cluster
    # Note: ctx.semantic.cluster_pass_rate takes the agent PACKAGE id, not instance id
    agent_package_id = "a7b2c1d0-..."  # resolved via admin tooling
    rate = await ctx.semantic.cluster_pass_rate(agent_package_id, cluster)

    decision = await self._decide(order, ctx)

    # Autopilot only when the cluster has mature test coverage AND recent passes
    if (
        decision.structured["decision"] == "approve"
        and decision.structured["confidence"] >= 0.9
        and rate
        and rate.pass_rate >= 0.95
        and rate.total >= 10
    ):
        # Safe to auto-approve
        await ctx.capability.call("tickets.reply", ticket_id=req.payload["ticket_id"], body="...")
        return decision

    # Otherwise park for human review
    await ctx.human.request(kind="refund", tier="T1", summary="...", detail=decision.structured)
    return decision

CI integration#

A CI step that fails on eval regressions:

YAML
# .github/workflows/agent-eval.yml
- name: Upload agent for eval
  run: |
    konstera agent upload --manifest manifest.json --image $IMAGE
- name: Run eval
  run: |
    konstera eval run io.konstera.refund-handler --fail-on 0.9
    # fails CI if pass rate < 0.9 across any cluster

(Note: konstera eval run ships in CLI v0.2.0 — Phase 3 of the dev-stack roadmap. Until then, trigger via the portal + check pass rates manually.)

Pitfalls#

  • Non-deterministic eval: if _decide() calls random.random(), scenarios will pass/fail randomly. Keep eval deterministic — mock anything stochastic.
  • Fixtures drift from reality: if _decide() logic uses fields the fixture doesn't carry, you'll pass eval but fail real invocations. Add a scenario that mirrors a known-failure production invocation to guard against this.
  • Over-reliance on cluster pass rate: a 95% pass rate on 10 samples isn't the same as 95% on 10,000. Gate on rate.total >= N as well as rate.pass_rate.
  • agent_id confusion: ctx.semantic.cluster_pass_rate() takes the agent package UUID, not the instance UUID. Map via tenant_agent_instances.agent_id → agent_packages.agent_id.

Common extensions#

  • Golden-replay regression: on new agent version upload, replay the N most recent production invocations (not just manifest scenarios). Compares old vs. new structured output.
  • Human-in-the-loop learning: when a reviewer rejects a decision, write a new eval scenario from the invocation + their reason. Over time the eval suite captures the real-world edge cases.
  • A/B eval: konstera eval compare v0.2.0 v0.3.0 — same scenarios against two versions, structured diff of responses.

See also#