Pattern Composition¶
Two primitives for building multi-step agentic pipelines out of simpler patterns.
PatternChain — sequential piping¶
from brain.patterns import PatternChain, RAGAgent, ReflexionAgent
chain = PatternChain([
RAGAgent(retriever=my_retriever), # step 1: retrieve context
ReflexionAgent(max_iterations=2), # step 2: self-critique
])
result = chain.run("What is our auth strategy?")
print(result.answer)
# Inspect per-step results
for step in result.metadata["chain_steps"]:
print(f"[{step['pattern']}] {step['answer'][:80]}")
Custom transform¶
By default, the previous pattern's answer becomes the next task. Override with transform_fn:
chain = PatternChain(
[rag_agent, reflexion_agent],
transform_fn=lambda result, i: f"Improve this answer: {result.answer}",
)
Failure handling¶
# Stop on first failure (default)
chain = PatternChain([p1, p2], stop_on_failure=True)
# Continue even if a step fails
chain = PatternChain([p1, p2], stop_on_failure=False)
PatternRouter — conditional dispatch¶
from brain.patterns import PatternRouter, RAGAgent, ReActAgent
router = PatternRouter(
routes={
"sql": RAGAgent(retriever=db_retriever),
"research": ReActAgent(tools={"search": web_search}),
},
route_fn=lambda task: "sql" if "SELECT" in task.upper() else "research",
default="research",
)
result = router.run("How many events were logged last week?")
print(result.metadata["route"]) # "sql"
print(result.metadata["pattern"]) # "RAGAgent"
API Reference¶
brain.patterns.compose.PatternChain
¶
PatternChain(patterns: list[BasePattern], transform_fn: TransformFn | None = None, stop_on_failure: bool = True)
Bases: BasePattern
Run patterns sequentially, piping output to input.
Each pattern receives the previous pattern's answer as its task
(or the result of a custom transform_fn). The final PatternResult
contains the last pattern's answer; full per-step detail is in
result.metadata["chain_steps"].
If any step fails and stop_on_failure=True (default), the chain
returns immediately with ok=False. If stop_on_failure=False,
the raw answer from the failed step is forwarded and the chain continues.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patterns
|
list[BasePattern]
|
Ordered list of |
required |
transform_fn
|
TransformFn | None
|
Called as |
None
|
stop_on_failure
|
bool
|
Stop and return if any pattern returns |
True
|
Source code in brain/patterns/compose.py
run
¶
Execute the chain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
str
|
Initial input passed to the first pattern. |
required |
Returns:
| Type | Description |
|---|---|
PatternResult
|
PatternResult with the final pattern's answer. |
PatternResult
|
|
PatternResult
|
|
Source code in brain/patterns/compose.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
brain.patterns.compose.PatternRouter
¶
Bases: BasePattern
Route a task to one of several patterns based on a routing function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
routes
|
dict[str, BasePattern]
|
Dict mapping route label → |
required |
route_fn
|
RouteFn
|
Callable |
required |
default
|
str | None
|
Fallback label if |
None
|
Source code in brain/patterns/compose.py
run
¶
Route task to the appropriate pattern and run it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
str
|
The question or instruction for the agent. |
required |
Returns:
| Type | Description |
|---|---|
PatternResult
|
PatternResult from the selected pattern. |
PatternResult
|
|
PatternResult
|
|
PatternResult
|
|
Source code in brain/patterns/compose.py
brain.patterns.compose.ChainStepRecord
dataclass
¶
ChainStepRecord(step_index: int, pattern_name: str, task: str, answer: str, iterations: int, ok: bool, error: str | None = None)
Metadata for one pattern's execution within a PatternChain run.
Composition patterns¶
| Pipeline | When to use |
|---|---|
| RAG → Reflexion | Retrieve context, then self-critique the answer |
| PlanExecute → RAG | Plan steps, then retrieve evidence for each |
| Router → Chain | Route to a multi-step pipeline by query type |
| Chain → HITL | Run steps, then require human approval of the final action |