# AMI SDK - Python Client

Python SDK for Memrail AMI (Adaptive Memory Intelligence) API.

## Installation

```bash
# Create virtual environment (requires Python 3.9+)
python3.12 -m venv .venv
source .venv/bin/activate

# Install from PyPI
pip install memrail

# Or install locally for development
pip install -e .
```

## Quick Start

```python
from memrail import AMIClient, atoms as A

# Environment-driven config
client = AMIClient()  # Reads AMI_API_KEY, AMI_WORKSPACE, AMI_PROJECT from env

# Build context atoms
ctx = [
    A.state("user.id", "U-123"),
    A.tag("segment", "new"),
    A.event("user.completed.onboarding_step", ts=datetime.utcnow(),
            subject_anchor=("user", "U-123")),
]

# Invoke AMI decision engine
resp = client.invoke(atoms=ctx, trace=True)

# Handle selected actions
for sel in resp.selected:
    if sel.action:
        handle_action(sel.action)
        client.ack(activation_id=sel.activation_id, status="acknowledged")
```

## Features

- ✅ Type-safe atom builders (state, tag, event)
- ✅ Invoke with idempotency, dry-run, top-k
- ✅ Event ingestion (single, batch, buffered)
- ✅ EMU authoring & lifecycle management
- ✅ ACK activations & retrieve traces
- ✅ Production-ready: retries, timeouts, error taxonomy
- ✅ Thread-safe HTTP client with connection pooling
- ✅ CLI tool for EMU registration and validation
- ✅ Local DSL validation for fast feedback

## CLI Tool

The SDK includes an `ami` command-line tool for managing EMUs.

### Setup

```bash
# Activate virtual environment
source .venv/bin/activate

# Configure environment
cp .env.example .env
# Edit .env with your credentials:
#   AMI_API_KEY=your-api-key
#   AMI_ORG=your-org
#   AMI_WORKSPACE=development
#   AMI_PROJECT=your-project

# Verify CLI is available
ami --help
```

### Commands

```bash
# Initialize a new project
ami init my_project

# Validate EMUs locally (fast, no API call)
memrail validate --project my_project

# Validate a specific JSON file
memrail validate --file projects/my_project/emus/json/seed.json

# Register EMUs with API
memrail register-emu --project my_project

# Register from a specific JSON file
memrail register-emu --file projects/my_project/emus/json/seed.json

# Dry-run (validate server-side without persisting)
memrail register-emu --project my_project --dry-run

# List discovered EMUs
ami list --project my_project

# Work with all projects
memrail validate --all
memrail register-emu --all
```

### EMU File Formats

EMUs can be defined in Python or JSON format:

**JSON format** (`emus/json/seed.json`):
```json
{
  "emus": [
    {
      "emu_key": "myproject.welcome_user",
      "trigger": "state.user.is_new AND NOT event.agent.sent.welcome IN 'P7D'",
      "action": {
        "type": "tool_call",
        "intent": "Send welcome message",
        "tool": {"tool_id": "messaging", "version": "1.0.0", "args": {}}
      },
      "policy": {"mode": "auto", "priority": 5},
      "expected_utility": 0.8,
      "confidence": 0.9,
      "state": "draft"
    }
  ]
}
```

### DSL Trigger Syntax

| Syntax | Example | Description |
|--------|---------|-------------|
| Boolean | `state.user.premium` | True if exists and truthy |
| Comparison | `state.tier == 'gold'` | String/numeric comparison |
| IN list | `state.role IN ['admin', 'owner']` | Membership check |
| EXISTS | `state.email EXISTS` | Check if key exists |
| Event recency | `event.user.login IN 'PT1H'` | Event within duration |
| COUNT | `COUNT event.click IN 'PT1H' > 5` | Count events |
| NOT/AND/OR | `state.active AND NOT state.banned` | Logical operators |

See [docs/02-dsl-reference.md](docs/02-dsl-reference.md) for complete DSL reference.

### Project Structure

```
projects/
├── project_a/
│   └── emus/
│       ├── customer_support.py   # Python EMU definitions
│       └── json/
│           └── seed.json         # JSON EMU definitions
└── project_b/
    └── emus/
        └── sales_automation.py
```

## Prompt Registry CLI

The SDK includes commands for managing prompts in the Prompt Registry.

### Setup

```bash
# Set environment variables (or use --workspace and --project flags)
export AMI_WORKSPACE=development
export AMI_PROJECT=my-project
```

### Prompt Commands

```bash
# List all prompts
ami prompt-list
ami prompt-list --folder onboarding    # Filter by folder
ami prompt-list --category system      # Filter by category
ami prompt-list --format json          # Output as JSON

# Get a prompt
ami prompt-get <slug>
ami prompt-get welcome-email --version 2    # Get specific version

# Create a prompt
ami prompt-create <slug> <name> --content "Your prompt content"
ami prompt-create welcome-email "Welcome Email" --content "Hello {{name}}"
ami prompt-create intro "Intro" --content "Welcome!" --folder onboarding

# Update a prompt (creates new version)
ami prompt-update <slug> --content "Updated content"
ami prompt-update welcome-email --content "Hello {{name}}, welcome!"

# Delete a prompt
ami prompt-delete <slug>

# Move prompt to a folder
ami prompt-move <slug> <folder_path>
ami prompt-move welcome-email onboarding
ami prompt-move welcome-email              # Move to root

# List versions of a prompt
ami prompt-versions <slug>

# Activate/rollback to a specific version
ami prompt-activate <slug> <version>
ami prompt-activate welcome-email 2

# View prompt analytics
ami prompt-analytics <slug>
ami prompt-analytics welcome-email --period 30d
```

### Folder Commands

```bash
# Create a folder
ami prompt-folder-create <path> <name>
ami prompt-folder-create onboarding "Onboarding"
ami prompt-folder-create support/tier-1 "Tier 1 Support"

# List folders
ami prompt-folder-list
ami prompt-folder-list --parent onboarding

# Delete a folder
ami prompt-folder-delete <path>
ami prompt-folder-delete onboarding --force    # Move prompts to root
```

### Advanced Options

The `prompt-create` command supports these advanced options:

```bash
ami prompt-create my-prompt "My Prompt" \
  --content "Hello {{name}}" \
  --folder onboarding \
  --description "A greeting prompt" \
  --category system \
  --model claude-3-sonnet \
  --max-tokens 1000 \
  --max-length 5000 \
  --temperature 0.7 \
  --tags "greeting,onboarding"
```

| Option | Description |
|--------|-------------|
| `--content`, `-c` | Prompt template content |
| `--content-file`, `-F` | Read content from file |
| `--folder` | Folder path (e.g., "onboarding/tier-1") |
| `--description`, `-d` | Description of the prompt |
| `--category` | Category: system, user, assistant, tool |
| `--model`, `-m` | Target LLM model (e.g., claude-3, gpt-4) |
| `--max-tokens` | Token budget for the prompt |
| `--max-length` | Character limit |
| `--temperature` | Sampling temperature (0.0-2.0) |
| `--tags`, `-t` | Comma-separated tags |
| `--dry-run`, `-n` | Validate without creating |

### Template Variables

Prompts support `{{variable}}` syntax for template variables:

```bash
ami prompt-create greeting "Greeting" --content "Hello {{name}}, welcome to {{company}}!"
```

The `variables` field in the response will automatically contain `["name", "company"]`.

## Documentation

See [docs/SDK_DESIGN_AND_SPEC.md](../docs/SDK_DESIGN_AND_SPEC.md) for full specification.

## Development

```bash
# Install dependencies
uv pip install -e ".[dev]"

# Run SDK tests
uv run pytest ../sdk_tests/ -v

# Run unit tests only
uv run pytest ../sdk_tests/unit/ -v

# Run integration tests (requires API running)
uv run pytest ../sdk_tests/integration/ -v
```
