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: RAG agent

A complete working recipe. The agent takes a customer question, pulls relevant policy snippets from the vector store, feeds them to the LLM with grounding instructions, and returns a grounded answer. Pass it to ctx.human.request() if you want approval before send.

What you'll have at the end
A policy Q&A agent that answers customer questions only from indexed policy snippets, cites them inline, and parks each answer for reviewer approval before it is sent.
You need
Policy snippets already indexed (ingestion agent or initialize())konstera-sdk==0.6.0A model bound to the narrator purpose
RoleDetail
Readsctx.vector (query), ctx.llm (complete)
Writesnone (grounded response is a draft until a reviewer approves)
Prerequisitespolicy snippets already indexed via a separate ingestion agent or in initialize()

How the agent works#

A production RAG setup is really two jobs sharing one vector namespace: an ingestion job that keeps shared:policies up to date, and the Q&A agent that reads from it on every question.

FlowIndex once, then retrieve → ground → approve on every question Interactive — click a block
SequenceOne question, end to end
CallerRAG agentctx.vectorctx.llm1question2query shared:policies3top-5 hits + metadatano hits → return a visible failure4system + numbered snippets5answer citing [1], [3]6draft → reviewer inbox

The three files#

  1. Write the handler — main.py

    Validate the input, retrieve the top 5 chunks, build a numbered grounded prompt, generate, and return the answer with structured provenance.

    Python
    from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run
    
    
    class RagAgent(Agent):
        """Grounded Q&A over a shared policy knowledge base."""
    
        async def handle(
            self, req: AgentRequest, ctx: AgentContext
        ) -> AgentResponse:
            question = req.input.strip()
            if not question:
                return AgentResponse(content="Please ask a question.")
    
            await ctx.log.info("rag.start", question_len=len(question))
    
            # 1. Retrieve top-5 relevant chunks
            hits = await ctx.vector.query(
                namespace="shared:policies",
                query_text=question,
                top_k=5,
            )
    
            if not hits:
                await ctx.log.warn("rag.no_hits")
                return AgentResponse(
                    content="I couldn't find any relevant policy. Please contact support.",
                    structured={"hits": 0},
                )
    
            # 2. Build a grounded prompt
            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}"
    
            # 3. Generate — kernel routes 'narrator' purpose to the tenant's bound model
            result = await ctx.llm.complete(
                prompt=user,
                system=system,
                purpose="narrator",
                temperature=0.1,
            )
    
            await ctx.log.info(
                "rag.done",
                hits=len(hits),
                top_score=hits[0].score,
                cost_usd=result.cost_usd,
                tokens=result.input_tokens + result.output_tokens,
            )
    
            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],
                },
            )
    
    
    if __name__ == "__main__":
        run(RagAgent())
    
  2. Declare the contract — manifest.json

    "autonomy": "require_review" is what makes the answer a draft: the handler's result lands in the reviewer inbox, where the reviewer picks send / edit / redraft / reject (see Manifest reference). The llmRequirements entry declares the narrator purpose the handler calls.

    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)",
      "description": "Answers customer questions grounded in indexed policy snippets.",
      "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,
        "cpuMillis": 500
      },
      "input": {
        "type": "object",
        "required": ["question"],
        "properties": {
          "question": {
            "type": "string",
            "description": "The customer's question."
          }
        }
      },
      "llmRequirements": [
        {
          "purpose": "narrator",
          "suggestedModel": "claude-sonnet-4-6",
          "maxTokens": 1024,
          "description": "Generates a grounded answer from policy snippets."
        }
      ],
      "capabilities": { "needs": [] }
    }
    
  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"]
    

Indexing the policies (one-off job)#

Separate from the RAG agent — this runs once or on policy updates. Can be a scheduled agent, a CI step, or a one-shot script against the kernel's MCP endpoint directly.

Python
# ingest.py — example scheduled-ingestion agent
from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run


class IngestAgent(Agent):
    async def handle(
        self, req: AgentRequest, ctx: AgentContext
    ) -> AgentResponse:
        # In real life, pull from source-of-truth (CMS, docs repo, etc.)
        policies = [
            {
                "id": "policy-refund-window",
                "text": "Refunds within 30 days of delivery are automatic.",
                "source": "handbook.pdf",
                "page": 7,
            },
            {
                "id": "policy-return-condition",
                "text": "Items must be in original condition with tags attached.",
                "source": "handbook.pdf",
                "page": 7,
            },
        ]

        for p in policies:
            await ctx.vector.upsert(
                namespace="shared:policies",
                content=p["text"],
                external_id=p["id"],
                metadata={"source": p["source"], "page": p["page"]},
            )

        return AgentResponse(
            content=f"Indexed {len(policies)} policies.",
            structured={"indexed": len(policies)},
        )


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

Deploy this with a schedules[] entry in its manifest to re-index weekly, or trigger it from a webhook when the policy source updates — see the Scheduled cron agent recipe.

Common extensions#

ExtensionWhen you need itHow
Hybrid retrievalNumeric policy references (e.g. "30 days")Combine vector hits with a BM25 keyword search. Add via ctx.connector.call() against a search service.
RerankingBetter ordering from a wider candidate setPull top-20 from vector then rerank via a separate model. Call rerank through ctx.capability.call('tools.rerank', ...) or a connector; record cost via ctx.cost.record(kind='tool', ...).
Reviewer gateAnswers must be approved before sendingSet autonomy: require_review (already set in the manifest above) so the drafted answer parks in the inbox for approval before sending.
Per-tenant namespacesPolicies vary by jurisdictionChange namespace from shared:policies to shared:policies:${ctx.tenant_id}:${jurisdiction}.

Pitfalls#

Do
  • Check for empty results: always check len(hits) == 0 and return a visible failure — empty results can mask a dead index. A silent "I don't know" is worse than an error.
  • Rely on top-K ordering, not an absolute score threshold.
  • Sanitise before concatenating into the prompt if the index ever accepts user-generated content.
Avoid
  • Filter hits by score > 0.X without calibration — the kernel's stub embedder returns deterministic but not semantically meaningful scores until M10.
  • Treat retrieved content as automatically safe: policy snippets come from trusted sources (usually your own CMS), but user-generated content in the index opens the door to prompt injection via retrieved content.
Before you ship
  • Policy snippets are indexed in the namespace the agent queries, and an ingest job (schedule or webhook) re-indexes on policy updates.
  • Every upsert carries an external_id and source metadata so answers are traceable.
  • Zero hits returns a visible failure, not a silent "I don't know".
  • The system prompt forbids invented policy and asks for inline citations.
  • No score > 0.X filter unless it has been calibrated.
  • User-generated content is sanitised before it reaches the prompt.
  • autonomy: require_review is set so answers park for approval before sending.
  • The LLM call uses purpose=, and rag.start / rag.done logs are in place.

See also#