K9-AIF: Architecture-First Framework for Governed, Modular Agentic AI Systems
pip install k9-aif==1.18.8 Copy PIP instructions
K9-AIF is an architecture-first framework for designing governed, enterprise-scale multi-agent AI systems.
Unlike agent runtimes that focus mainly on execution, K9-AIF defines the architectural structure, interaction boundaries, governance model, and runtime execution control needed to build scalable agentic AI systems.
The framework separates Architecture Building Blocks (ABB) from Solution Building Blocks (SBB), enabling extensible and composable agentic applications.
K9-AIF layered architecture — click the image to view full resolution.
K9-AIF provides architectural patterns for constructing agentic workflows where multiple AI agents collaborate to perform reasoning, analysis, and decision-support tasks while maintaining clear governance, orchestration, and integration boundaries.
The framework draws inspiration from established architectural disciplines, including:
The goal is to enable composable, scalable, and governed agentic AI applications.
Start here for a structured explanation of K9-AIF:
K9-AIF separates architecture into abstract ABB contracts and concrete SBB implementations.
Architecture Building Blocks define abstract architectural capabilities and contracts within the K9-AIF framework. ABBs specify responsibilities, interfaces, and interaction patterns without prescribing concrete implementations or technologies.
Solution Building Blocks provide concrete implementations of ABB contracts. SBBs introduce domain-specific behavior, technology choices, and runtime integrations while conforming to the architectural constraints defined by the ABB layer.
This separation allows architectural stability while enabling domain-specific extensions without modifying the core framework.
A typical K9-AIF system is organized into a set of architectural layers that separate interface concerns, orchestration, external integration, inference, and persistence.
K9-AIF introduces the concept of Agent Squads.
A Squad represents a coordinated group of agents working together to perform a specific capability within an orchestration workflow.
Rather than orchestrators invoking individual agents directly, K9-AIF introduces a structured collaboration layer between orchestrators and agents.
Event → K9EventRouter (single entry point) ├── event_type known ──────────────────► domain topic └── event_type unknown ──► intent.in │ IntentOrchestrator → IntentSquad → K9IntentAgent ├── intent resolved ──► domain topic └── intent unclear ──► responses.out domain topic → Orchestrator → Squads → Agents → LLM Squads allow enterprise workflows to be modeled as capability-based teams of agents. All squad-level execution remains subject to K9-AIF’s governance and Zero Trust execution controls, ensuring that agent actions are verified and policy-enforced at runtime.
Squads are defined declaratively using configuration and loaded dynamically at runtime using the SquadLoader component.
An orchestrator knows only squads (1.18.1). It loads a squad by YAML file and squad id (self.squads.load_one(squad_yaml, squad_id)) and never names, imports or builds an agent. Squads are YAML (agents:, flow:, synthesis:) run by BaseSquad, so a squad needs no Python of its own; an application may add one common Squad(BaseSquad) for squad-level behaviour. SquadLoader.from_agents(...) is built once at the application's entry point and passed to every orchestrator. The test: if a squad's agents change, the orchestrator is unaffected. Enforced by K9X Inspector rule K9-DEC-002 and a Claude Code hook.
A squad's agents run in sequence, and by default each step receives the original payload plus every earlier agent's full output. The prompt grows with every step. The squad coordinator bounds that growth.
squads: ClaimsSquad: synthesis: auto # off (default) | auto | always # or: synthesis: {mode: auto, max_context_chars: 24000, agent: MySynthesizerAgent} flow: - agent: IntakeAgent - agent: AssessmentAgent - agent: AuditAgent synthesis: false # this step always gets the full results The synthesizer is not a squad member. It is never listed under agents: or flow: and never runs as a step. The squad holds it on the side:
When a step gets a digest. Before each step the squad checks:
When all four hold, the step receives squad_digest (with squad_digest_keys) in place of the upstream outputs. The same set of upstream results is digested once and reused. Full outputs stay in the squad's results, and squad_synthesis logs each digest (step, source keys, sizes in and out) for audit.
The synthesizer is an ordinary governed BaseAgent, so Shield and Guardian screen its digest like any agent output. Squads with a single agent never synthesize. Scaffolds generated by K9X Studio set synthesis: auto on every squad with two or more agents; below the threshold, those squads behave exactly as before.
Since 1.15, governance is a property of the runtime, not something each agent must remember to call:
Every control is listed in the security capability catalog, capabilities.yaml, mapped to the OWASP Top 10 for LLM Applications and the OWASP agentic threats, with each control's limits and the known gaps. K9X Sentinel judges new AI-security research against it every day, and K9X SATAN attacks a running application to prove the controls hold.
Once you understand the execution hierarchy (Router → Orchestrator → Squads → Agents), Zero Trust is the cross-cutting layer that governs every step of it.
Traditional Zero Trust focuses on access — who can reach a system. K9-AIF applies Zero Trust to execution — every action is verified before it runs.
Zero Trust is opt-in (enable_zero_trust). When enabled, it is enforced at two layers:
Zero Trust is not a checkpoint — it is a layer applied across the system.
An Agent or Squad can trigger a human decision mid-flow — a fraud score below an auto-approve threshold, a low-confidence classification, a policy that always requires sign-off — by raising RequiresHIL, a first-class exception rather than a return-value flag your Squad author has to remember to check.
Two rules govern how this crosses the framework's existing layers, both deliberate, documented carve-outs rather than accidents:
The Orchestrator never blocks waiting for a decision — a human review can take hours or days. It returns {"status": "pending_hil", ...} immediately; K9EventRouter picks the decision back up later by subscribing across every hil.replies.* topic (one consumer, pattern- subscribed — never one Kafka topic per job) and resolving by correlation_id against a persisted hil_pending row, then re-routing the resumed payload through its own route() — resuming a workflow is just re-routing it with new information now available, not a second mechanism.
Agents decide on what they are given. If that is last night's extract, or a record read when the flow started, an agent can release a payment another system paid a minute ago. The context fabric keeps live state current from your event streams (Kafka, Confluent, Redpanda) and gives it to agents, every value stamped with as_of, age_seconds, stale and the event that set it.
k9x Origin (1.18) puts all of this behind one call. An agent asks get_current(entity, id); Origin answers from live state, reads through to the system of record when needed, verifies before irreversible steps, flags quarantine and conflicts, and screens the request and the answer with k9x Shield. It states facts; business rules (K9RulesAgent) decide, for example "a claim over $5,000 goes to a person". Configured in config/origin.yaml; design: k9x Origin design.
Agents still never subscribe to Kafka. Recipe: Developer Guide 15.7. Reference application: K9X Streams.
Prototype systems based on K9-AIF demonstrate how the framework can support governed multi-agent architectures across multiple domains.
K9X Enterprise Insurance Operations Center (EOC) → examples/K9X_Enterprise_Insurance_OperationsCenter
The EOC is the canonical reference implementation of K9-AIF — the most complete, production-aligned example in the framework. It demonstrates every architectural concept end-to-end:
Use the EOC as your reference when building any new K9-AIF solution.
DAS turns capability documents into JCIDS, acquisition and systems-engineering deliverables aligned with DoDAF 2.0. It is built entirely on K9-AIF: 1 router, 4 stage orchestrators, 5 YAML squads and 17 agents, all SBBs extending framework ABBs. → github.com/k9aif/dow-k9x · Live: das.k9x.ai
K9-AIF is designed to support the development of governed, modular agentic AI systems aligned with enterprise architecture practices.
The framework bridges traditional enterprise architecture principles with emerging agentic AI system design.
Many of the architectural ideas used within the K9-AIF framework are documented separately as reusable architecture patterns.
These patterns describe the core design principles behind the framework while remaining independent of any specific runtime implementation.
The full set of patterns is available in the K9-AIF Architecture Patterns repository:
An in-framework pattern for iterative hypothesis-validate-reason workflows — applicable across security, fraud, claims, compliance, and document extraction domains.
Implemented as BaseValidationLoopAgent in k9_aif_abb/k9_agents/validation/. K9ValidationLoopAgent is the OOB LLM-driven implementation for confidence-convergence loops. K9PlanningLoopAgent (k9_aif_abb/k9_agents/planning/) is the dynamic-planning sibling — the agent builds and revises its own step plan each iteration, finalizing when the plan is complete. See Skill 10 in SKILLS.md for usage and the SA decision guide.
One contract, two out-of-box convergence strategies: domain SBBs extend K9ValidationLoopAgent when the question is "is this hypothesis true, and am I confident enough?" (e.g. FraudDetectionAgent in the EOC example), or K9PlanningLoopAgent when it is "what's left on my plan?" (InvestigationAgent is an illustrative name).
A development-time pipeline for grading authored prompts — system prompts, agent instructions, and guided-flow templates — before they reach a workflow.
BasePromptEvaluator defines the ABB contract: evaluate(), compare(), and run_suite(). K9PromptEvaluator is the OOB SBB — LLM-as-judge, five weighted dimensions (correctness 35%, completeness 25%, format compliance 15%, clarity 15%, relevance 10%), grade scale A–F, configurable PASS threshold. EvaluationFactory.create(config) provisions the right implementation.
This is a design-time and measurement-time tool, not a runtime gate. Runtime quality enforcement is K9ValidationLoopAgent's responsibility. The K9Chat reference application ships with an evaluation toggle that grades every response in real time during development.
Implemented in k9_aif_abb/k9_agents/evaluation/. Config key: evaluation.provider: k9.
Agents never name a model. Every call goes through llm_invoke to K9ModelRouter, which picks one from the model catalog in two layers.
Rules (cold start). Weighted scoring on the request: task-type capability (+3), latency tier (+2) and cost tier (+2). The default_model is the fallback. On a tie, the conversation's current model wins (session affinity).
Evidence (learned routing, since 1.13). This works like evaluation-trained routers such as Not Diamond and RouteLLM. The router keeps graded outcomes: which model scored what, 0 to 100, on which prompt. For a new prompt, it predicts each model's quality from its scores on the most similar prompts it has seen. It then subtracts a penalty for latency or cost the request can't afford. If the best prediction beats the rules' pick by a margin, the evidence decides. Routing is per prompt: two reasoning prompts can go to different models.
router.record_feedback(prompt, model_alias="smart", quality=88, task_type="reasoning") Graders, evaluators, HIL reviewers or K9X Arena (head-to-head model matches) supply the evidence. With none, the router behaves exactly as the rules say.
Guard rails evidence can't cross. A confidential request goes only to confidential-capable models when the catalog has any. A model whose recent calls mostly failed is skipped (circuit breaker). Every decision records why it was made.
Configure under inference.router.learning (all keys optional; see config.yaml). Inference-layer documentation: k9_aif_abb/k9_inference
K9-AIF uses a Provider Adapter pattern to support multiple LLM backends without coupling any framework component to a specific provider.
LLMFactory remains provider-agnostic — it resolves the correct adapter from ProviderAdapterRegistry and asks it to construct the BaseLLM. Agents, squads, orchestrators, and the model router require no changes when switching providers.
inference: llm_factory: backend: ollama base_url: "http://localhost:11434" models: general: model: "llama3.2:1b" OpenAI:
inference: llm_factory: backend: openai api_key_env: OPENAI_API_KEY # resolved from environment — never hardcode models: general: model: "gpt-4o-mini" Grok / xAI:
from k9_aif_abb.k9_core.inference.base_provider_adapter import BaseProviderAdapter from k9_aif_abb.k9_core.inference.provider_registry import ProviderAdapterRegistry class BedrockProviderAdapter(BaseProviderAdapter): @property def provider_name(self) -> str: return "bedrock" def create_llm(self, model_name, factory_cfg, extra_kwargs): return BedrockLLM(model=model_name, **extra_kwargs) # your BaseLLM implementation ProviderAdapterRegistry.register("bedrock", BedrockProviderAdapter) Then set backend: bedrock in config.yaml. Nothing else changes.
API keys are always resolved from environment variables (api_key_env: MY_KEY) — never stored in config files.
K9-AIF can be applied to enterprise AI systems that require governed orchestration of multiple AI capabilities.
K9X Studio is a browser-based drag-and-drop architecture builder for K9-AIF systems.
This is where every K9-AIF application starts: design your architecture visually → generate a production-ready scaffold → implement the SBBs (VS Code + Claude Code recommended).
➡️ https://studio.k9x.ai — source: k9aif/k9x-ecosystem
K9X Studio generates the framework-compliant scaffold and hands it to the SBB Architect / PM, who builds on K9-AIF and publishes the finished SBB to K9X Enterprise Continuum for SBB → ABB promotion. At runtime, K9-AIF publishes human-review tasks over Kafka to K9X HIL. Continuum's artifact governance is separate from the framework's runtime execution governance (k9x_Shield governance on every agent by construction, and the opt-in Zero Trust layer).
Products built on top of K9-AIF, beyond the framework itself:
Source for all of the above: k9aif/k9x-ecosystem
Every K9-AIF application follows the same lifecycle, whether or not you use Claude Code:
The core implementation of the K9-AIF architecture is provided in the k9_aif_abb package, where ABB refers to Architecture Building Blocks.
This package contains the Architecture Building Blocks (ABB) and supporting framework components used to construct K9-AIF applications.
A comprehensive developer guide for contributors and solution developers building on K9-AIF is available in the docs/developers/ folder.
The guide covers all 31 chapters — from core architecture and ABB/SBB development model through agent, orchestrator, and router development; the Validation Loop and Critic-Actor iterative reasoning patterns; model routing, governance, testing standards, and developer workflow. It includes accurate class signatures, config examples, and code drawn directly from the k9_aif_abb source.
K9-AIF is designed to work with Claude Code — Anthropic's AI coding assistant. The repository includes context files that give Claude Code an immediate, accurate understanding of the framework so you can build new applications without re-explaining the architecture every session.
Open the repository in VS Code with Claude Code and run this prompt:
You are building a new application example on top of the K9-AIF framework located at k9_aif_abb/. Project details: - Application name: [e.g., K9X_Healthcare_ClaimsProcessor] - Create all files under: examples/K9X_Healthcare_ClaimsProcessor/ - Spec doc location: examples/K9X_Healthcare_ClaimsProcessor/docs/your-spec.docx Before writing any code, read CLAUDE.md and SKILLS.md, then read the canonical reference example: examples/K9X_Enterprise_Insurance_OperationsCenter/ Then implement the new example following the same structure and conventions. Rules: - Every agent must extend BaseAgent and implement execute() - Every squad must be defined in a squad YAML with a flow - The router must route by event_type - Enable security.shield (with ingress and egress check lists) in the app's config.yaml — every agent is governed by construction, and production refuses ungoverned agents - Folder structure, naming, and config patterns must match the reference example The combination of CLAUDE.md, SKILLS.md, and the reference example gives Claude Code enough context to generate architecturally consistent, governed, runnable K9-AIF applications from a spec document alone.
Read more: Build a K9-AIF Example App in Minutes Using Claude Code
The repository also ships .claude/settings.json, which wires eight PostToolUse hooks — Python syntax check, YAML validation, ABB test run, governance check, __init__.py docstring check, single-model-path (llm_invoke) check, README link check, and orchestrator-knows-only-squads check (see the Hooks section of CLAUDE.md) — that run automatically whenever Claude Code writes or edits a file.
Each hook command uses an absolute path (e.g. /Users/ /k9-aif-framework/.claude/hooks/check-python.sh). After cloning, edit .claude/settings.json and replace the path prefix with the absolute path of your own clone, or the hooks will fail with "command not found".
To use the framework in your own project, install it from PyPI:
pip install k9-aif # core pip install "k9-aif[kafka,postgres]" # with extras; "k9-aif[all]" for everything To run the bundled demos, clone the framework and create a Python virtual environment:
git clone https://github.com/k9aif/k9-aif-framework.git cd k9-aif-framework python3.11 --version python3.11 -m venv .venv source .venv/bin/activate python --version python -m pip install --upgrade pip python -m pip install -r requirements.txt Then run the bundled demo from the k9-aif-framework folder:
./run_acme_support_center.sh (k9chat moved to its own repo, k9-aif-examples — clone it as a sibling directory and see its k9chat/README.md for setup and run instructions.)
pytest k9_aif_abb/tests/ -v # all pytest k9_aif_abb/tests/test_framework.py -v # one file Project Status K9-AIF is an actively evolving framework. The repository contains reference architecture material, prototype implementations, and example applications used to explore practical approaches to building governed agentic AI systems.
This repository is released under the Apache License 2.0.
The framework concepts may be used, adapted, and extended for research and development of agentic AI systems.
Contributions, discussions, and architectural ideas related to agentic AI systems and multi-agent orchestration are welcome.
K9-AIF draws inspiration from established software architecture and enterprise architecture practices, including:
The K9-AIF blog contains architecture discussions, design evaluations, and evolving ideas related to building governed agentic AI systems.
Before building, understand the architecture. K9-AIF is built on a strict ABB/SBB separation — Architecture Building Blocks define the contracts, Solution Building Blocks implement the domain. Read CLAUDE.md for architecture and SKILLS.md for step-by-step recipes. These are the two documents that will make you productive fast.
Every K9-AIF application starts in K9X Studio — with or without Claude Code. Describe the architecture on the drag-and-drop canvas and click Generate Scaffold to get a framework-compliant, runnable project. See the K9-AIF Developer Journey section above for the full lifecycle.
To implement domain logic on the Studio scaffold, the most effective tool is Claude Code inside VS Code.
K9-AIF ships with CLAUDE.md and SKILLS.md — these are loaded automatically by Claude Code, giving it a deep understanding of the framework's architecture, conventions, and code generation rules. Claude Code will extend the generated agents, squads, orchestrators, and config in ways that comply with the framework, without you having to explain the patterns each time.
Download and install Claude Code from: https://claude.ai/code
It is available as a VS Code extension, a desktop app, and a CLI. Once installed, open your solution folder in VS Code and Claude Code is ready to use.
To check a solution, run k9aif inspect : the framework's k9_inspect checks it statically against 28 conformance rules (ABB contracts, three-layer decoupling, llm_invoke, Kafka ownership, governance by construction, secrets, private IPs, squad/agent YAML). Add --fail-on violation in CI to fail the build on a violation; K9X Inspector runs the same rules on every push.
Building Architecture-First Agentic Applications — done right, that really works.
Ravi Natarajan AI Systems Architect Agentic AI • Multi-Agent Systems • LLM Applications
Email: ravinatarajan@k9x.ai Website: https://k9x.ai
kafka postgres oidc neo4j crewai claude-agent-sdk langgraph chromadb server s3 ibm-cos openai mcp redis docling all
agentic-ai multi-agent governance llm enterprise-ai
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.
Yanked reason: Broken with MCP SDK 2.x; use 1.12.4
Yanked reason: G-19: HIL replies never consumed on a real broker, despite the G-16 fix in this version. Fixed in 1.12.2.
Yanked reason: Known bug (G-16): duplicate HIL replies could re-route an already-resumed flow. Fixed in 1.12.1.




