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
| Pattern | The problem it answers | In K9-AIF |
|---|---|---|
| Agent Squad | Agents build on each other's findings, and someone has to wire every hand-off. | BaseSquad |
| Squad Layer | Every change to a team of agents means editing the orchestrator. | SquadLoader.from_agents |
| Validation Loop | Some answers have to be earned by testing, not computed in one pass. | BaseValidationLoopAgent |
| Critic-Actor | A first draft is rarely good enough, and the writer can't judge it. | BaseCriticActorAgent |
| Event Router | Some events say what they want; others don't. | K9EventRouter |
| Model Router | Model choice is written into agent code. | K9ModelRouter |
| Inference Layer | Agents import a provider's client and are stuck with it. | BaseLLM, LLMFactory |
| Provider Adapter | Secrets, caches and models move between vendors. | SecretManagerFactory, CacheFactory |
| LLM Invoke Chain | Every agent solves routing, audit and retries its own way. | llm_invoke() |
| Factory | Construction logic is scattered and ungoverned. | LLMFactory, RouterFactory |
| Runtime Agent Loader | Changing a flow means a code change and a redeploy. | AgentLoader, SquadLoader |
| External Connector | Agents call outside systems with no check at the boundary. | BaseConnector |
| Classified Orchestration | Everything 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.

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
- The orchestrator loads a squad by id.
- The squad's YAML lists its agents and the order they run in.
- Each agent runs and writes its result under its
result_keyin the shared context. - The next agent receives the enriched context.
- 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.

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
- The squad's YAML names its agents and its flow.
- The entry point builds one squad loader with
SquadLoader.from_agents()and hands it to every orchestrator. - The orchestrator calls
load_one(squad_yaml, squad_id). Squads only. - The loader reads each agent's own YAML (
classandmodule) and builds it. - One
<App>Squad(BaseSquad)per application holds squad-level behaviour, such asbefore_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.

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
generate_hypothesis()forms the next thing to test from the steps so far.run_validation()calls a tool, a rules engine, a model or an outside system.evaluate_observation()reads the result and returns a confidence.should_continue()returns continue, finalize, escalate or fail.- The step is recorded and the loop repeats, or ends in
finalize(),escalate()orfail().
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.

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
generate(): the actor writes the first draft.critique(): the critic returns structured feedback.refine(): the actor revises against the feedback.should_accept(): the critic decides.- Repeat, or end in
finalize(),escalate()orfail().
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.

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
| Outcome | What happens |
|---|---|
| Known | The event_type is in the routing table. The router publishes to the domain topic. No model call. |
| Unknown, resolved | The router publishes to intent.in. The intent orchestrator classifies the event and publishes it to the domain topic. |
| Unclear | Confidence 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.

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
- The agent sends an
InferenceRequest: prompt,task_type, sensitivity,latency_budget,cost_profile. - 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.
- Eligible models are scored: task type +3, sensitivity +2, latency tier +2, cost tier +2.
- Learned routing can move the choice to a model that has done better on similar prompts.
- 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.

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
BaseLLMis the contract (ABB).OllamaLLM,OpenAILLM,AzureOpenAILLM,WatsonxLLMandMockLLMimplement it.ProviderAdapterRegistrymaps a provider name to its adapter.LLMFactorybuilds the configured provider and caches it by alias.- 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.

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
- A
Base…class is the contract, for exampleBaseSecretManagerorBaseCache. - Adapters implement it per vendor.
- The factory keeps a registry from name to adapter and reads the choice from configuration.
- With no configuration, a safe default works.
- Credentials never sit in
config.yaml; they come from the environment or the secret store.
| Contract | Adapters |
|---|---|
BaseSecretManager | EnvSecretAdapter, VaultSecretAdapter, AwsSecretAdapter, IbmSecretAdapter |
BaseCache | InMemoryAdapter, RedisAdapter |
BaseLLM | Ollama, 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.

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
- The agent calls
llm_invoke(config, InferenceRequest). ModelRouterFactoryreturns the cached router.- The router returns a
RouteDecision. LLMFactory.get(alias)returns the cached model.- The model runs; the decision is stored with its latency and scores.
- An
InferenceResponsegoes 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.

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
- A factory class keeps a registry from name to class.
register(name, cls)adds to it; configuration picks one.get(name)returns a cached instance and fails on an unknown name.- 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.

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
- Each agent has its own YAML naming its
classandmodule. AgentLoaderbuilds the agent and merges its YAML with the global configuration (merge_with_global()).- Squad YAML lists the squad's agents and flow steps, each with a
result_key. SquadLoaderreads the squad YAML and builds the agents it names.- 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.

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
- A connector hides the protocol; the connector type comes from configuration.
- The tool call is screened before it leaves (
@govern_tool_call) and the result is screened when it returns (@govern_tool_result). - With the tool gate on, each call is checked against a tool registry, logged, and can pause for a person.
- 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.

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.
| Signal | Path | Adapter |
|---|---|---|
| Service task, REST API | Deterministic | BaseApiAdapter (HttpApiAdapter) |
| Business rule task, policy | Deterministic | BaseRulesAdapter (K9RulesAdapter, RestRulesAdapter, GoRulesAdapter) |
| Data read or write, SQL | Deterministic | BaseDataAdapter (SqlDataAdapter) |
| Send or receive, Kafka, SQS | Deterministic | BaseMessagingAdapter (contract) |
| Workflow engine, BPM process | Deterministic | BaseWorkflowAdapter, BaseBpmAdapter (contracts) |
| Reasoning, extraction, ambiguity | Agentic | Squad, 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 pattern | In K9-AIF | What K9-AIF adds |
|---|---|---|
| Pipes and Filters | Agent squad, sequential flow | Shared context, governance on each step |
| Scatter-Gather | Parallel squads: execute_squads(parallel=True) | Results keyed by squad, one trace id; a request for a person cancels the rest |
| Content-Based Router | K9EventRouter | One entry point, intent fallback |
| Content Enricher | Each agent enriches the shared context | An enrichment contract across the squad |
| Process Manager | Orchestrator | Squad coordination, governance, Zero Trust |
| Publish-Subscribe Channel | Kafka topics per domain | The router publishes, orchestrators consume |
| Wire Tap | Governance before and after each agent | Enforced in production |
| Canonical Data Model | The shared context payload | One payload from router to squad to agent |
| Correlation Identifier | correlation_id in the payload | One trace id per run; a paused run resumes by it |
| Message Store | Session context | Redis, SQLite or in-memory, chosen in configuration |
| Dead Letter Channel | Retry with backoff, then <topic>.dlq | A message that can't be decoded or resolved goes there with the reason |
| Idempotent Receiver | Planned |
Reference: G. Hohpe and B. Woolf, Enterprise Integration Patterns, Addison-Wesley, 2003. Diagrams and notes for each pattern are also in the patterns repository.
K9X