> ## 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.

# Quickstart

> Build your first AXON program in minutes

## Your First AXON Program

Let's build a complete AXON program that analyzes documents. You'll learn the core concepts while creating something functional.

<Note>
  This guide assumes you've completed the [installation](/axon-docs/axon-docs/installation) and have at least one API key configured.
</Note>

## Step 1: Create Your First .axon File

Create a file called `analyzer.axon`:

```axon analyzer.axon theme={null}
persona Analyst {
  domain: ["analysis", "research"]
  tone: professional
  confidence_threshold: 0.8
}

flow AnalyzeText(input: Document) -> Summary {
  step Extract {
    given: input
    ask: "What are the key points in this text?"
    output: KeyPoints
  }
  
  step Summarize {
    given: Extract.output
    ask: "Create a concise summary"
    output: Summary
  }
}
```

<Steps>
  <Step title="Understand the persona block">
    The `persona` defines the cognitive identity of your AI:

    ```axon theme={null}
    persona Analyst {
      domain: ["analysis", "research"]
      tone: professional
      confidence_threshold: 0.8
    }
    ```

    * `domain`: Areas of expertise
    * `tone`: Communication style
    * `confidence_threshold`: Minimum confidence level (0-1)
  </Step>

  <Step title="Understand the flow block">
    The `flow` defines a pipeline of cognitive steps:

    ```axon theme={null}
    flow AnalyzeText(input: Document) -> Summary {
      step Extract { ... }
      step Summarize { ... }
    }
    ```

    Flows:

    * Take typed inputs (`input: Document`)
    * Return typed outputs (`-> Summary`)
    * Execute steps sequentially
    * Pass data between steps
  </Step>
</Steps>

## Step 2: Validate Your Syntax

Before running, check that your syntax is correct:

```bash theme={null}
axon check analyzer.axon
```

<CodeGroup>
  ```text Success theme={null}
  ✓ Lexer: 23 tokens
  ✓ Parser: AST built
  ✓ Type Checker: No errors

  analyzer.axon is valid.
  ```

  ```text Error Example theme={null}
  ✗ Parse error at line 5, column 12:
    Expected 'output:' after ask statement
  ```
</CodeGroup>

<Tip>
  Always use `axon check` during development to catch errors early. It runs the lexer, parser, and type checker without executing anything.
</Tip>

## Step 3: Compile to IR

Compile your AXON program to Intermediate Representation (IR):

```bash theme={null}
axon compile analyzer.axon
```

This creates `analyzer.ir.json` - a JSON representation of your program that any backend can execute.

<Accordion title="View the generated IR">
  The IR is a JSON structure that captures the semantic meaning of your program:

  ```json theme={null}
  {
    "type": "program",
    "personas": [
      {
        "name": "Analyst",
        "domain": ["analysis", "research"],
        "tone": "professional",
        "confidence_threshold": 0.8
      }
    ],
    "flows": [
      {
        "name": "AnalyzeText",
        "parameters": [{"name": "input", "type": "Document"}],
        "return_type": "Summary",
        "steps": [...]
      }
    ]
  }
  ```
</Accordion>

## Step 4: Execute Your Program

Run your AXON program with a specific backend:

```bash theme={null}
axon run analyzer.axon --backend anthropic
```

<Tabs>
  <Tab title="Anthropic (Claude)">
    ```bash theme={null}
    axon run analyzer.axon --backend anthropic
    ```

    Requires `ANTHROPIC_API_KEY` environment variable.
  </Tab>

  <Tab title="OpenAI (GPT)">
    ```bash theme={null}
    axon run analyzer.axon --backend openai
    ```

    Requires `OPENAI_API_KEY` environment variable.
  </Tab>

  <Tab title="Gemini">
    ```bash theme={null}
    axon run analyzer.axon --backend gemini
    ```

    Requires `API_KEY_GEMINI` environment variable.
  </Tab>

  <Tab title="Ollama (Local)">
    ```bash theme={null}
    axon run analyzer.axon --backend ollama
    ```

    Requires Ollama running locally with a model pulled.
  </Tab>
</Tabs>

## Step 5: Add Constraints with Anchors

Now let's add hard constraints that can never be violated:

```axon analyzer.axon theme={null}
persona Analyst {
  domain: ["analysis", "research"]
  tone: professional
  confidence_threshold: 0.8
}

anchor NoSpeculation {
  require: factual_claims
  confidence_floor: 0.75
  unknown_response: "Insufficient information to answer"
  on_violation: raise AnchorBreachError
}

flow AnalyzeText(input: Document) -> Summary {
  step Extract {
    given: input
    ask: "What are the key points in this text?"
    output: KeyPoints
  }
  
  step Summarize {
    given: Extract.output
    ask: "Create a concise summary"
    validate: NoSpeculation
    output: Summary
  }
}
```

<Warning>
  Anchors are **hard constraints**. If violated, AXON's self-healing runtime will retry with failure context. If max attempts are exceeded, it raises `AnchorBreachError`.
</Warning>

## Step 6: Add Self-Healing with Refine

Make your program automatically retry and self-correct:

```axon analyzer.axon theme={null}
flow AnalyzeText(input: Document) -> Summary {
  step Extract {
    given: input
    ask: "What are the key points in this text?"
    output: KeyPoints
  }
  
  step Summarize {
    given: Extract.output
    ask: "Create a concise summary"
    validate: NoSpeculation
    if confidence < 0.8 -> refine(max_attempts: 2)
    output: Summary
  }
}
```

The `refine` directive:

* Automatically retries when confidence is too low
* Injects failure context back to the LLM
* Respects max attempts to prevent infinite loops
* Creates a closed feedback loop for self-healing

## Step 7: Enable Execution Tracing

Get detailed insights into what happened during execution:

```bash theme={null}
axon run analyzer.axon --backend anthropic --trace
```

This saves a trace to `analyzer.trace.json`. View it with:

```bash theme={null}
axon trace analyzer.trace.json
```

<Accordion title="Example trace output">
  ```text theme={null}
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  AXON Execution Trace
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  [FLOW_START] AnalyzeText
    timestamp: 2026-03-06T14:23:01.234Z
    input: {"text": "Sample document..."}

    [STEP_START] Extract
      timestamp: 2026-03-06T14:23:01.235Z
    
    [MODEL_CALL] anthropic/claude-3-5-sonnet
      timestamp: 2026-03-06T14:23:01.240Z
      duration: 1.23s
    
    [STEP_COMPLETE] Extract
      output: {"key_points": [...]}
      confidence: 0.92
    
    [STEP_START] Summarize
      timestamp: 2026-03-06T14:23:02.470Z
    
    [VALIDATION_SUCCESS] NoSpeculation
      timestamp: 2026-03-06T14:23:03.120Z
    
    [STEP_COMPLETE] Summarize
      output: {"summary": "..."}
      confidence: 0.89

  [FLOW_COMPLETE] AnalyzeText
    timestamp: 2026-03-06T14:23:03.125Z
    duration: 1.89s
    status: success
  ```
</Accordion>

## Advanced Example: Contract Analyzer

Here's a production-ready example from the AXON repository:

```axon contract_analyzer.axon theme={null}
persona LegalExpert {
  domain: ["contract law", "IP", "corporate"]
  tone: precise
  confidence_threshold: 0.85
  cite_sources: true
}

context LegalReview {
  memory: session
  language: "en"
  depth: exhaustive
  max_tokens: 4096
  temperature: 0.3
}

anchor NoHallucination {
  require: source_citation
  confidence_floor: 0.75
  unknown_response: "I don't have sufficient information."
  on_violation: raise AnchorBreachError
}

type RiskScore(0.0..1.0)

type Party {
  name: FactualClaim,
  role: FactualClaim
}

type Risk {
  score: RiskScore,
  mitigation: Opinion?
}

tool WebSearch {
  provider: brave
  max_results: 5
  timeout: 10s
}

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
  }
}

run AnalyzeContract(myContract)
  as LegalExpert
  within LegalReview
  constrained_by [NoHallucination]
  on_failure: retry(backoff: exponential)
  output_to: "report.json"
  effort: high
```

This example demonstrates:

<CardGroup cols={2}>
  <Card title="Personas" icon="user">
    Specialized domain expertise with citation requirements
  </Card>

  <Card title="Context" icon="brain">
    Session configuration for consistent behavior
  </Card>

  <Card title="Anchors" icon="anchor">
    Hard constraints preventing hallucination
  </Card>

  <Card title="Types" icon="shapes">
    Custom semantic types with ranges and optional fields
  </Card>

  <Card title="Tools" icon="wrench">
    External capabilities with timeout configuration
  </Card>

  <Card title="Flows" icon="diagram-project">
    Multi-step pipelines with data passing
  </Card>
</CardGroup>

## Using the Python API

You can also use AXON programmatically:

```python theme={null}
from axon import Lexer, Parser, TypeChecker, IRGenerator, get_backend

# Read source
source = open("analyzer.axon").read()

# Compile
tokens = Lexer(source).tokenize()
ast = Parser(tokens).parse()
errors = TypeChecker(ast).check()

if errors:
    for error in errors:
        print(f"Error: {error}")
    exit(1)

# Generate IR and execute
ir = IRGenerator().generate(ast)
backend = get_backend("anthropic")
result = backend.compile(ir)

print(f"Result: {result}")
```

## Common CLI Commands

Here's a quick reference of useful commands:

```bash theme={null}
# Validate syntax
axon check program.axon

# Compile to IR
axon compile program.axon -b openai

# Execute with tracing
axon run program.axon --backend anthropic --trace

# View trace
axon trace program.trace.json

# Check version
axon version
```

## Error Hierarchy

AXON has a six-level error hierarchy:

| Level | Error               | When it occurs                |
| ----- | ------------------- | ----------------------------- |
| 1     | `ValidationError`   | Output type mismatch          |
| 2     | `ConfidenceError`   | Confidence below floor        |
| 3     | `AnchorBreachError` | Anchor constraint violated    |
| 4     | `RefineExhausted`   | Max retry attempts exceeded   |
| 5     | `RuntimeError`      | Model call failed             |
| 6     | `TimeoutError`      | Execution time limit exceeded |

<Tip>
  Levels 1-3 trigger automatic self-healing via the `RetryEngine`. Level 4 means healing failed after max attempts.
</Tip>

## Next Steps

<CardGroup cols={2}>
  <Card title="Language Reference" icon="book" href="/axon-docs/axon-docs/language/syntax-overview">
    Deep dive into AXON's syntax and semantics
  </Card>

  <Card title="Type System" icon="shapes" href="/axon-docs/axon-docs/concepts/type-system">
    Learn about epistemic types and subsumption
  </Card>

  <Card title="Examples" icon="flask" href="/axon-docs/axon-docs/examples/contract-analyzer">
    Real-world AXON programs
  </Card>

  <Card title="CLI Reference" icon="terminal" href="/axon-docs/axon-docs/cli/overview">
    Complete CLI documentation
  </Card>
</CardGroup>
