> ## Documentation Index
> Fetch the complete documentation index at: https://ricardovelit.com/axon-docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Flow

> Build cognitive pipelines with steps, reasoning, and semantic operations

## Overview

A **flow** is AXON's equivalent of a function—a composable cognitive pipeline that takes typed inputs and produces typed outputs. Unlike traditional functions, flows contain **cognitive primitives** like reasoning, probing, and validation rather than loops and assignments.

## Syntax

```axon theme={null}
flow <Name>(<param>: <Type>, ...) -> <ReturnType> {
  // Flow body: steps and cognitive operations
  step <Name> { ... }
  probe <target> for [...]
  reason { ... }
  validate <target> against <Schema> { ... }
  weave [...] into <output>
}
```

## Basic Structure

### Simple Flow

```axon theme={null}
flow Summarize(doc: Document) -> Summary {
  step Extract {
    given: doc
    ask: "Extract key points"
    output: KeyPoints
  }
}
```

### Multi-Step Flow

```axon theme={null}
flow AnalyzeContract(doc: Document) -> ContractAnalysis {
  step Extract {
    given: doc
    ask: "Extract all parties, obligations, dates, and penalties"
    output: EntityMap
  }
  
  step Assess {
    given: Extract.output
    ask: "Identify ambiguous or risky clauses"
    output: RiskAnalysis
  }
}
```

## Parameters

Flows can accept typed parameters:

```axon theme={null}
// Single parameter
flow Process(input: Document) -> Report { ... }

// Multiple parameters
flow Compare(doc1: Document, doc2: Document) -> Comparison { ... }

// Different types
flow Score(text: String, threshold: Float) -> RiskScore { ... }
```

## Return Types

Flows declare their return type after `->`:

```axon theme={null}
flow ExtractEntities(doc: Document) -> EntityMap { ... }

flow CalculateRisk(data: FinancialData) -> RiskScore { ... }

flow Synthesize(parts: List<Section>) -> Report { ... }
```

Return type can be omitted if the flow doesn't return a value:

```axon theme={null}
flow LogActivity(event: Event) {
  // No return type
  step Record { ... }
}
```

## Step

**Steps** are named cognitive operations within a flow.

### Basic Step

```axon theme={null}
step Extract {
  given: doc
  ask: "Extract all parties and their roles"
  output: PartyList
}
```

### Step Fields

| Field              | Purpose                  | Required |
| ------------------ | ------------------------ | -------- |
| `given`            | Input data or expression | Optional |
| `ask`              | Instruction or question  | Optional |
| `output`           | Output type              | Optional |
| `confidence_floor` | Minimum confidence       | Optional |

### Referencing Step Outputs

Reference previous step outputs using dot notation:

```axon theme={null}
step First {
  given: input
  output: IntermediateResult
}

step Second {
  given: First.output     // Reference First's output
  output: FinalResult
}
```

### Multiple Inputs

```axon theme={null}
step Combine {
  given: [StepA.output, StepB.output]
  ask: "Merge the results"
  output: Combined
}
```

## Probe

**Probe** performs targeted extraction of specific fields from data.

### Syntax

```axon theme={null}
probe <target> for [<field>, <field>, ...]
```

### Examples

```axon theme={null}
// Standalone probe
probe document for [parties, dates, obligations, penalties]

// Within a step
step Extract {
  given: doc
  probe doc for [parties, obligations]
  output: EntityMap
}
```

### Use Cases

* Extract structured fields from documents
* Pull specific entities from text
* Parse formatted data into fields

## Reason

**Reason** performs explicit chain-of-thought reasoning.

### Syntax

```axon theme={null}
reason [<name>] {
  given: <input>
  about: <topic>
  ask: <question>
  depth: <integer>
  show_work: <boolean>
  chain_of_thought: <boolean>
  output: <Type>
}
```

### Examples

```axon theme={null}
// Basic reasoning
reason {
  given: Extract.output
  ask: "What are the potential risks?"
  output: RiskAnalysis
}

// Named reasoning with depth
reason RiskAssessment {
  given: EntityMap
  about: "contractual obligations"
  depth: 3
  show_work: true
  output: DetailedRisks
}

// Chain of thought
reason {
  given: problem
  chain_of_thought: true
  depth: 5
  output: Solution
}
```

### Fields

| Field              | Type       | Default | Purpose                |
| ------------------ | ---------- | ------- | ---------------------- |
| `given`            | Expression | —       | Input data             |
| `about`            | String     | —       | Topic or focus         |
| `ask`              | String     | —       | Question to answer     |
| `depth`            | Integer    | 1       | Reasoning depth (1-10) |
| `show_work`        | Boolean    | false   | Show reasoning steps   |
| `chain_of_thought` | Boolean    | false   | Explicit CoT reasoning |
| `output`           | Type       | —       | Output type            |

### Depth Guidelines

* **1-2**: Simple, direct reasoning
* **3-4**: Moderate complexity, multiple factors
* **5-7**: Complex, multi-step reasoning
* **8-10**: Deep, exhaustive analysis

## Validate

**Validate** creates semantic validation checkpoints with conditional actions.

### Syntax

```axon theme={null}
validate <target> against <Schema> {
  if <condition> -> <action>
  if <condition> -> <action>
}
```

### Examples

```axon theme={null}
validate Assess.output against RiskSchema {
  if confidence < 0.80 -> refine(max_attempts: 2)
  if structural_mismatch -> raise ValidationError
}

validate result against OutputFormat {
  if incomplete -> refine(max_attempts: 3)
  if confidence < 0.75 -> warn "Low confidence result"
  if passes -> pass
}
```

### Validation Actions

| Action   | Syntax                    | Purpose               |
| -------- | ------------------------- | --------------------- |
| `refine` | `refine(max_attempts: N)` | Retry with refinement |
| `raise`  | `raise ErrorName`         | Raise an error        |
| `warn`   | `warn "message"`          | Emit warning          |
| `pass`   | `pass`                    | Accept result         |

### Conditions

Conditions can use comparison operators:

```axon theme={null}
if confidence < 0.8 -> refine(max_attempts: 2)
if score >= 0.95 -> pass
if length == 0 -> raise EmptyResultError
if status != valid -> warn "Invalid status"
```

## Refine

**Refine** implements adaptive retry logic with failure context.

### Syntax

```axon theme={null}
refine {
  max_attempts: <integer>
  pass_failure_context: <boolean>
  backoff: <strategy>
  on_exhaustion: <action>
}
```

### Examples

```axon theme={null}
refine {
  max_attempts: 3
  pass_failure_context: true
  backoff: exponential
  on_exhaustion: escalate
}

refine {
  max_attempts: 5
  backoff: linear
  on_exhaustion: raise MaxAttemptsError
}
```

### Fields

| Field                  | Values                                 | Default | Purpose                       |
| ---------------------- | -------------------------------------- | ------- | ----------------------------- |
| `max_attempts`         | Integer ≥ 1                            | 3       | Maximum retry attempts        |
| `pass_failure_context` | Boolean                                | true    | Include failure info in retry |
| `backoff`              | `none`, `linear`, `exponential`        | `none`  | Backoff strategy              |
| `on_exhaustion`        | `raise X`, `escalate`, `fallback(...)` | —       | Action when exhausted         |

## Weave

**Weave** synthesizes multiple outputs into a coherent result.

### Syntax

```axon theme={null}
weave [<source>, ...] into <target> {
  format: <type>
  priority: [<field>, ...]
  style: <string>
}
```

### Examples

```axon theme={null}
// Basic weave
weave [Extract.output, Assess.output] into FinalReport

// With formatting
weave [EntityMap, RiskAnalysis, LegalPrecedents] into Report {
  format: StructuredReport
  priority: [risks, recommendations, summary]
  style: "executive summary"
}

// Multiple sources
weave [
  Introduction.output,
  Analysis.output,
  Conclusion.output
] into Document {
  format: LongForm
}
```

### Requirements

* Minimum 2 sources required
* Sources must be valid step outputs or identifiers
* Target is the output identifier

## Use Tool

**Use** invokes external tool capabilities.

### Syntax

```axon theme={null}
use <ToolName>(<argument>)
```

### Examples

```axon theme={null}
// Within a step
step Research {
  use WebSearch("quantum computing 2025")
  output: SearchResults
}

// Direct usage
use WebSearch("AXON programming language")

use DatabaseQuery("SELECT * FROM contracts WHERE status='active'")
```

## Memory Operations

### Remember

Store data to semantic memory:

```axon theme={null}
remember(<expression>) -> <MemoryTarget>
```

```axon theme={null}
remember(ResearchSummary) -> LongTermKnowledge

step Store {
  given: ImportantFinding
  remember(ImportantFinding) -> ProjectMemory
}
```

### Recall

Retrieve data from semantic memory:

```axon theme={null}
recall(<query>) from <MemorySource>
```

```axon theme={null}
recall("quantum computing") from ResearchKnowledge

step Retrieve {
  recall("previous analysis") from ProjectMemory
  output: PriorContext
}
```

## Conditionals

Conditional branching in flows:

### Syntax

```axon theme={null}
if <condition> -> <step>
else -> <step>
```

### Examples

```axon theme={null}
if confidence < 0.5 -> step Retry {
  ask: "Re-analyze with more detail"
}
else -> step Accept {
  output: FinalResult
}

if score >= 0.9 -> step HighConfidence {
  output: Approved
}

if length == 0 -> step HandleEmpty {
  ask: "Generate default response"
}
else -> step Process {
  given: result
}
```

## Complete Example

Here's a comprehensive flow using multiple features:

```axon theme={null}
flow AnalyzeContract(doc: Document, threshold: Float) -> ContractReport {
  
  step Extract {
    given: doc
    probe doc for [parties, obligations, dates, penalties]
    output: EntityMap
  }
  
  reason RiskAssessment {
    given: Extract.output
    about: "contractual risks"
    ask: "Identify ambiguous or risky clauses"
    depth: 3
    show_work: true
    output: RiskAnalysis
  }
  
  validate RiskAssessment.output against RiskSchema {
    if confidence < threshold -> refine(max_attempts: 2)
    if structural_mismatch -> raise ValidationError
    if confidence >= threshold -> pass
  }
  
  use WebSearch("relevant legal precedents")
  
  step ComparePrece dents {
    given: [RiskAssessment.output, SearchResults]
    ask: "Compare findings with legal precedents"
    output: ComparativeAnalysis
  }
  
  weave [
    Extract.output,
    RiskAssessment.output,
    ComparativAnalysis.output
  ] into FinalReport {
    format: StructuredReport
    priority: [risks, obligations, recommendations]
  }
  
  remember(FinalReport) -> ContractDatabase
}
```

## Run Statements

Execute flows using `run` statements:

### Basic Execution

```axon theme={null}
run AnalyzeContract(myContract)
```

### With Modifiers

```axon theme={null}
run AnalyzeContract(myContract, 0.85)
  as LegalExpert
  within LegalReview
  constrained_by [NoHallucination]
  on_failure: retry(backoff: exponential)
  output_to: "report.json"
  effort: high
```

### Run Modifiers

| Modifier         | Purpose            | Example                                   |
| ---------------- | ------------------ | ----------------------------------------- |
| `as`             | Specify persona    | `as LegalExpert`                          |
| `within`         | Specify context    | `within ProductionContext`                |
| `constrained_by` | Apply anchors      | `constrained_by [NoHallucination]`        |
| `on_failure`     | Error handling     | `on_failure: retry(backoff: exponential)` |
| `output_to`      | Output destination | `output_to: "result.json"`                |
| `effort`         | Effort level       | `effort: high`                            |

### Effort Levels

* `low`: Minimal resources, fast execution
* `medium`: Balanced (default)
* `high`: More thorough, slower
* `max`: Maximum resources, exhaustive

### Failure Strategies

```axon theme={null}
on_failure: log                          // Just log the error
on_failure: retry(backoff: exponential)  // Retry with backoff
on_failure: escalate                     // Escalate to handler
on_failure: raise CustomError            // Raise specific error
```

## Best Practices

### 1. Name Steps Descriptively

```axon theme={null}
// Good
step ExtractEntities { ... }
step AssessRisks { ... }
step GenerateReport { ... }

// Avoid
step Step1 { ... }
step DoStuff { ... }
```

### 2. Use Appropriate Reasoning Depth

```axon theme={null}
// Simple extraction: shallow depth
step QuickScan {
  ask: "List main topics"
  // No explicit reasoning needed
}

// Complex analysis: deep reasoning
reason ComplexAnalysis {
  depth: 5
  show_work: true
}
```

### 3. Validate Critical Outputs

```axon theme={null}
step CriticalAnalysis {
  given: input
  output: ImportantResult
}

validate CriticalAnalysis.output against Schema {
  if confidence < 0.9 -> refine(max_attempts: 3)
  if structural_mismatch -> raise ValidationError
}
```

### 4. Chain Steps Logically

```axon theme={null}
flow Pipeline(input: Data) -> Result {
  step Parse { given: input }
  step Validate { given: Parse.output }
  step Transform { given: Validate.output }
  step Enrich { given: Transform.output }
  step Synthesize { given: Enrich.output }
}
```

### 5. Use Weave for Multiple Sources

```axon theme={null}
// Don't concatenate manually
step ManualCombine {
  given: [sourceA, sourceB]
  ask: "Combine these outputs"
}

// Use weave instead
weave [sourceA, sourceB] into Combined {
  format: StructuredReport
}
```

## Related

* [Types](/axon-docs/axon-docs/language/types) — Type system and type definitions
* [Anchor](/axon-docs/axon-docs/language/anchor) — Hard constraints and validation
* [Persona](/axon-docs/axon-docs/language/persona) — Agent identities
* [Context](/axon-docs/axon-docs/language/context) — Execution environments
* [Tools](/axon-docs/axon-docs/language/tools) — External capabilities
