K9X

Patterns

Thirteen patterns that come up whenever agents leave the prototype. None of them is new: most are old integration and object patterns applied to agents. Each one here is built in K9-AIF, with a link to the code.

At a glance

PatternThe problem it answersIn K9-AIF
Agent SquadAgents build on each other's findings, and someone has to wire every hand-off.BaseSquad
Squad LayerEvery change to a team of agents means editing the orchestrator.SquadLoader.from_agents
Validation LoopSome answers have to be earned by testing, not computed in one pass.BaseValidationLoopAgent
Critic-ActorA first draft is rarely good enough, and the writer can't judge it.BaseCriticActorAgent
Event RouterSome events say what they want; others don't.K9EventRouter
Model RouterModel choice is written into agent code.K9ModelRouter
Inference LayerAgents import a provider's client and are stuck with it.BaseLLM, LLMFactory
Provider AdapterSecrets, caches and models move between vendors.SecretManagerFactory, CacheFactory
LLM Invoke ChainEvery agent solves routing, audit and retries its own way.llm_invoke()
FactoryConstruction logic is scattered and ungoverned.LLMFactory, RouterFactory
Runtime Agent LoaderChanging a flow means a code change and a redeploy.AgentLoader, SquadLoader
External ConnectorAgents call outside systems with no check at the boundary.BaseConnector
Classified OrchestrationEverything goes through a model, even work a rules engine does better.BaseIntegrationAdapter

Agent Squad

Execution

A squad is a team of agents that runs as one unit. Its YAML sets the order. Each agent writes its result under a named key in a shared context, so the next agent starts with everything the earlier ones found.

Agent Squad pattern: an orchestrator calls a squad; the squad runs each flow step in order, each agent governed before and after, and writes the result under its result_key in a shared context

The problem

Agents built in isolation don't share state. Their outputs don't fit together, each one is governed differently, and when something goes wrong nobody can say which step caused it.

How it works

  1. The orchestrator loads a squad by id.
  2. The squad's YAML lists its agents and the order they run in.
  3. Each agent runs and writes its result under its result_key in the shared context.
  4. The next agent receives the enriched context.
  5. Governance runs before and after every agent step.

Independent squads can also run side by side: execute_squads(parallel=True).

In K9-AIF: BaseSquad, SquadLoader, execute_squads(). Used by every DAS stage. Code

Squad Layer

Execution

An orchestrator knows squads and nothing below them. The agents a squad needs are named in its own YAML and built by the squad layer, so changing a squad's agents never changes an orchestrator.

Squad Layer pattern: the entry point builds one squad loader; orchestrators load squads; the loader builds agents

The problem

Each layer should know only the layer below it. The common way to break that rule is quiet: the orchestrator builds its squads' agents. It imports none of them, it only lists their names and fills a registry, so import checks pass. Yet every change to a squad's team means editing the orchestrator.

How it works

  1. The squad's YAML names its agents and its flow.
  2. The entry point builds one squad loader with SquadLoader.from_agents() and hands it to every orchestrator.
  3. The orchestrator calls load_one(squad_yaml, squad_id). Squads only.
  4. The loader reads each agent's own YAML (class and module) and builds it.
  5. One <App>Squad(BaseSquad) per application holds squad-level behaviour, such as before_step.

In K9-AIF: SquadLoader.from_agents, BaseSquad.before_step; checked by inspection rule K9-DEC-002. Code

Validation Loop

Execution

The agent tests a hypothesis, looks at the result and decides whether to go again. It stops when it is confident enough, reaches a definite answer, or hits the iteration cap.

Validation Loop pattern class diagram

The problem

Fraud signal correlation, compliance gap analysis, document confidence scoring: the answer has to be earned by testing, not produced in one pass. A one-shot agent has no shape for that.

How it works

  1. generate_hypothesis() forms the next thing to test from the steps so far.
  2. run_validation() calls a tool, a rules engine, a model or an outside system.
  3. evaluate_observation() reads the result and returns a confidence.
  4. should_continue() returns continue, finalize, escalate or fail.
  5. The step is recorded and the loop repeats, or ends in finalize(), escalate() or fail().

In K9-AIF: BaseValidationLoopAgent, K9ValidationLoopAgent; the same skeleton plans in K9PlanningLoopAgent. Settings: confidence_threshold, max_iterations. Code

Critic-Actor

Execution

An actor writes a draft. A critic reviews it and returns structured feedback. The actor revises. The cycle repeats until the critic accepts or a round limit sends it to escalation.

Critic-Actor pattern class diagram

The problem

Contracts, reports, policy reviews and code need refinement, not only a correctness check. Generation and judgement in one prompt rarely converge. The validation loop asks "is it right?"; this pattern asks "is it good enough?"

How it works

  1. generate(): the actor writes the first draft.
  2. critique(): the critic returns structured feedback.
  3. refine(): the actor revises against the feedback.
  4. should_accept(): the critic decides.
  5. Repeat, or end in finalize(), escalate() or fail().

In K9-AIF: BaseCriticActorAgent, K9CriticActorAgent. Code

Event Router

Routing

One entry point for every event. When the event type is known, it goes straight to its orchestrator. When it isn't, a separate intent orchestrator works it out. Either way the sender gets an answer.

Event Router pattern: three routing outcomes

The problem

Some events carry a clear signal (the user picked "Report a claim"); others don't ("I need help with something"). Putting classification inside the router ties the two together, and every change in how you classify, from rules to a model, changes the router.

How it works

OutcomeWhat happens
KnownThe event_type is in the routing table. The router publishes to the domain topic. No model call.
Unknown, resolvedThe router publishes to intent.in. The intent orchestrator classifies the event and publishes it to the domain topic.
UnclearConfidence is below confidence_threshold. The intent orchestrator sends a "please clarify" reply to responses.out. Nothing is dropped.

The router doesn't know the intent orchestrator exists; it reads intent.in on its own. Same rule as everywhere else in K9-AIF: the router publishes, orchestrators consume.

In K9-AIF: K9EventRouter, IntentOrchestrator, IntentSquad, K9IntentAgent. Code

Model Router

Inference

The agent says what it needs. The router decides which model serves it. Agent code never names a model.

Model Router pattern: agent, router, model catalog and routing store

The problem

Agents that hard-code a model can't follow cost limits, latency needs or policy. Every new model means editing every agent.

How it works

  1. The agent sends an InferenceRequest: prompt, task_type, sensitivity, latency_budget, cost_profile.
  2. Eligibility first: only models whose catalog capabilities cover the request may serve it, and a confidential request reaches only models cleared for it. If none qualifies, the request fails; the router never substitutes.
  3. Eligible models are scored: task type +3, sensitivity +2, latency tier +2, cost tier +2.
  4. Learned routing can move the choice to a model that has done better on similar prompts.
  5. The decision, with its scores and latency, is stored.

In K9-AIF: BaseModelRouter, K9ModelRouter, ModelRouterFactory, RoutingStateStore. Code

Inference Layer

Inference

A contract for inference, with one implementation per provider. The provider changes in configuration, not in code.

Inference Layer pattern: BaseLLM contract with provider implementations

The problem

An agent that imports a provider's client is tied to it. Moving from Ollama to watsonx means touching every agent.

How it works

  1. BaseLLM is the contract (ABB).
  2. OllamaLLM, OpenAILLM, AzureOpenAILLM, WatsonxLLM and MockLLM implement it.
  3. ProviderAdapterRegistry maps a provider name to its adapter.
  4. LLMFactory builds the configured provider and caches it by alias.
  5. Agents call llm_invoke() and never touch the factory.

In K9-AIF: BaseLLM, LLMFactory, ProviderAdapterRegistry, InferenceRequest, InferenceResponse. Code

Provider Adapter

Inference and integration

The same split applied to every infrastructure concern: a stable contract, one adapter per vendor, and a factory that picks one from configuration.

Provider Adapter pattern class diagram

The problem

Secrets move from environment variables to Vault. Caching moves from memory to Redis. Model providers change. None of that should reach agent or orchestrator code.

How it works

  1. A Base… class is the contract, for example BaseSecretManager or BaseCache.
  2. Adapters implement it per vendor.
  3. The factory keeps a registry from name to adapter and reads the choice from configuration.
  4. With no configuration, a safe default works.
  5. Credentials never sit in config.yaml; they come from the environment or the secret store.
ContractAdapters
BaseSecretManagerEnvSecretAdapter, VaultSecretAdapter, AwsSecretAdapter, IbmSecretAdapter
BaseCacheInMemoryAdapter, RedisAdapter
BaseLLMOllama, OpenAI, Azure OpenAI, watsonx, Mock, K9XLiteLLMBridgeAdapter

In K9-AIF: SecretManagerFactory, CacheFactory, LLMFactory. Code

LLM Invoke Chain

Inference

One function for every model call. llm_invoke() chains the model router, the factory and the provider into a single recorded call.

LLM Invoke Chain class diagram

The problem

Every agent that calls a model faces the same questions: which model, at what cost and latency, is it allowed, and was the choice recorded? Answering them inline in each agent gives duplicated and inconsistent code, and calls nobody can audit.

How it works

  1. The agent calls llm_invoke(config, InferenceRequest).
  2. ModelRouterFactory returns the cached router.
  3. The router returns a RouteDecision.
  4. LLMFactory.get(alias) returns the cached model.
  5. The model runs; the decision is stored with its latency and scores.
  6. An InferenceResponse goes back to the agent.

In K9-AIF: llm_invoke(), used by every agent, including K9ValidationLoopAgent and K9CriticActorAgent. Code

Factory

Construction

Components are built in one place. Application code never instantiates an agent, router, orchestrator or model directly.

Factory pattern class diagram

The problem

Direct construction spreads configuration, caching and lifecycle across the codebase, ties code to concrete classes and leaves nothing to govern.

How it works

  1. A factory class keeps a registry from name to class.
  2. register(name, cls) adds to it; configuration picks one.
  3. get(name) returns a cached instance and fails on an unknown name.
  4. Access to the registry is locked, so it is safe across threads.

In K9-AIF: LLMFactory, RouterFactory, ModelRouterFactory, SecretManagerFactory, CacheFactory, PersistenceFactory, AgentRegistry, OrchestratorRegistry. Code

Runtime Agent Loader

Construction

Agents and squads are wired from YAML at start-up. The YAML is the assembly; the loader builds it.

Runtime Agent Loader pattern

The problem

When the flow lives in code, adding an agent to a squad or changing the order needs a code change and a redeploy.

How it works

  1. Each agent has its own YAML naming its class and module.
  2. AgentLoader builds the agent and merges its YAML with the global configuration (merge_with_global()).
  3. Squad YAML lists the squad's agents and flow steps, each with a result_key.
  4. SquadLoader reads the squad YAML and builds the agents it names.
  5. Orchestrators never reference agent classes.

In K9-AIF: AgentLoader, SquadLoader; K9X Studio writes the same YAML from its canvas. Code

External Connector

Integration

Agents reach outside systems through connectors, and the check happens at that boundary: APIs, databases, MCP servers.

External Connector pattern

The problem

An agent that calls an outside system directly skips governance, hides a dependency and can't be tested alone. Every outside call is a boundary that should be checked and logged.

How it works

  1. A connector hides the protocol; the connector type comes from configuration.
  2. The tool call is screened before it leaves (@govern_tool_call) and the result is screened when it returns (@govern_tool_result).
  3. With the tool gate on, each call is checked against a tool registry, logged, and can pause for a person.
  4. With on_behalf_of, the server receives a token naming the person who asked, not a shared service account.

In K9-AIF: BaseConnector with MCPStreamableHttpConnector, MCPHttpConnector, MCPStdioConnector; BaseMCPAgent; BaseToolDispatcher. Code

Classified Orchestration

Integration and execution

One orchestrator runs two kinds of path: agentic (a squad and a model) and deterministic (an integration adapter). The architect draws the line at design time. The model doesn't decide it at run time.

Classified Orchestration pattern class diagram

The problem

Teams make one of two mistakes: every task goes through a model, even when a rules engine or workflow is the right tool, or models are avoided and the system loses the reasoning it needs for classification, extraction and evidence.

How it works

Each task is classified when the application is designed, from its event type, BPMN task type or payload. The orchestrator follows that choice. Two shapes are common: run both paths for the same event and merge the results, or hand off to an adapter that starts a workflow with no model involved.

SignalPathAdapter
Service task, REST APIDeterministicBaseApiAdapter (HttpApiAdapter)
Business rule task, policyDeterministicBaseRulesAdapter (K9RulesAdapter, RestRulesAdapter, GoRulesAdapter)
Data read or write, SQLDeterministicBaseDataAdapter (SqlDataAdapter)
Send or receive, Kafka, SQSDeterministicBaseMessagingAdapter (contract)
Workflow engine, BPM processDeterministicBaseWorkflowAdapter, BaseBpmAdapter (contracts)
Reasoning, extraction, ambiguityAgenticSquad, agents, model

In K9-AIF: BaseIntegrationAdapter and its family, built by IntegrationAdapterFactory; Studio shows both paths on the canvas. Code

Where these come from

Most of these are Enterprise Integration Patterns (Hohpe and Woolf, 2003) applied to agents. K9-AIF didn't invent the ideas. What it adds is a contract for each one, governance on every step, and a record of what happened.

EIP patternIn K9-AIFWhat K9-AIF adds
Pipes and FiltersAgent squad, sequential flowShared context, governance on each step
Scatter-GatherParallel squads: execute_squads(parallel=True)Results keyed by squad, one trace id; a request for a person cancels the rest
Content-Based RouterK9EventRouterOne entry point, intent fallback
Content EnricherEach agent enriches the shared contextAn enrichment contract across the squad
Process ManagerOrchestratorSquad coordination, governance, Zero Trust
Publish-Subscribe ChannelKafka topics per domainThe router publishes, orchestrators consume
Wire TapGovernance before and after each agentEnforced in production
Canonical Data ModelThe shared context payloadOne payload from router to squad to agent
Correlation Identifiercorrelation_id in the payloadOne trace id per run; a paused run resumes by it
Message StoreSession contextRedis, SQLite or in-memory, chosen in configuration
Dead Letter ChannelRetry with backoff, then <topic>.dlqA message that can't be decoded or resolved goes there with the reason
Idempotent ReceiverPlanned

Reference: G. Hohpe and B. Woolf, Enterprise Integration Patterns, Addison-Wesley, 2003. Diagrams and notes for each pattern are also in the patterns repository.